Magic Number


Symptoms

  • A constant (other than the empty string; 0, 1, or perhaps 2; and a few other base cases) appears in the body of the code.

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.



Refactoring Workbook
Refactoring Workbook
ISBN: 0321109295
EAN: 2147483647
Year: 2003
Pages: 146

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net