Avoid “magic numbers”
《Code Complete》 SAYS:
Magic numbers are literal numbers such as 100 or 47524 that appear in the middle of a program without explanation.If your program in a language that supports named constants,use them instead.If you can’t use named constants,use global variables when it is feasible to.
Avoiding magic numbers yields three advantages:
- Changes can be made more reliably.If you use named constants,you won’t overlook one of the 100s, or change a 100 that refers to someting else.
- Changes can be made more easily.When the maxinum number of entries changes from
100 to 200,if you are using magic number you have to find all the 100s and chan**ge them to 200s.If you are use 100+1 or 100-1 you ‘ll also have to find all the 101s and 99s and change them from 201s to 199s.If you are using a named constands,you simply change the definition of the constant from 100 to 200 in one place. - Your code is more readable.
note:
Replacing numbers by constants makes sense if the number carries a meaning that is not inherently obvious by looking at its value alone.
For instance,1
2productType = 221; // BAD: the number needs to be looked up somewhere to understand its meaning
productType = PRODUCT_TYPE_CONSUMABLE; // GOOD: the constant is self-describing
On the other hand,1
2int initialCount = 0; // GOOD: in this context zero really means zero
int initialCount = ZERO; // BAD: the number value is clear, and there's no need to add a self-referencing constant name if there's no other meaning
In Java ,using constants may let programs run fast.