Magic Number
Symptoms
Causes
Someone needs a value, so they put it in the code. On its own, perhaps it's not so bad, but often there are other values derived from or dependent on it. For example, we'll have a string defined banana and a length variable of 6. If you change the string, you need to change the length variable; however, this is not obvious, and so a defect gets in.
This is often a simple form of duplication, and it's especially easy to spot.
What to Do
Replace Magic Number with Symbolic Constant for the special value. If the values are strings (e.g., the text of dialog boxes), you may want to put them in some sort of mapping facility. (This is a move toward internationalization, and it often reduces duplication as well.)
Payoff
Reduces duplication. Improves communication.
Contraindications
Tests are often more readable when they simply use the value they want, but even in that case you might pull out a symbolic constant when there are derived values involved.
If you've moved to a map solution, the keys must be coordinated between the code and the map.
 |