Don't Use Magic Numbers
Why you should avoid magic numbers, what numbers are not magic numbers and how you can enforce this practice with ESLintMagic numbers are numbers that are used in the code but lack obvious meaning.
They make code harder to read because you need to understand how the number is used in order to understand what it means.
Ideally, you should understand the number from simply reading the code.
Let’s look at some examples of code that uses magic numbers, how to fix it, and how to enforce no magic numbers with a lint rule.
Code With Magic Numbers
Here is some code that uses magic numbers. Can you understand what 0.2
and 0.07
mean?
Code Without Magic Numbers
The code without magic numbers is easier to understand, because we don’t have to read the code to understand what the numbers mean:
But we can still improve the readability of the code by extracting some of these expressions to variables:
These expressions are not self-explanatory, and you have to parse them in your head in order to understand them.
So we are taking the same principle of extracting magic numbers to named constants and applying it to the expressions in order to make our code more readable.
These are not magic numbers
The fact you use a number in your code and not a named constant doesn’t mean it’s a magic number. If the meaning of the number can be understood from simply reading it, then it’s not a magic number.
Here are some examples of numbers used in the code that are not magic numbers:
A constant file
It’s often a good practice to keep all constants in a separate file. This way, you can easily find them and update them. Here is an example of the previous code with a constants file:
Enforcing No Magic Numbers With ESLint
When it comes to these type of practices, it’s better to let ESLint handle the validation of it rather than relying only on code reviews. Besides being more reliable, it saves a bunch of time for the reviewers and gives developers an immediate feedback.
Fortunately ESLint provides the rule no-magic-numbers
,
You can also customize it to allow some numbers to be used in the code, change
0
to any other number to see it in action:
Summary
Magic numbers make your code harder to read because you need to understand how the number is used in order to understand what it means.
By extracting magic numbers to named constants, code becomes easier to understand as the meaning of the numbers is immediately clear.
You should also consider managing these constants in a separate file, and adding the no-magic-numbers
ESLint rule
to enforce this practice.