Replace Magic Number with Symbolic Constant
From CSSEMediaWiki
Revision as of 23:57, 14 October 2009 by Matthew Harward (Talk | contribs)
Any time that a number is hard coded into the text, it should be replaced by a constant value for that class.
Example
public int power10(int num) { int result = 1; for(int i = 0; i < 10; i++) { result *= num; } return result; }
Refactors into:
private static final int powerNum = 10; ... public int power10(int num) { int result = 1; for(int i = 0; i < powerNum; i++) { result *= num; } return result; }
Arguably the 0 and 1 magic numbers should also be refactored.
See Also: