IfSQ
SPM-1—Magic Numbers
Defect Indicators: Numeric literals (other than 0 or 1) have been embedded directly into the source code. For example “34” or “86400”.
Risks: If numbers are embedded in code in this way, it increases the time needed to make maintenance changes, and increases the risk of error.
Assessment:
- Mark all the lines that contain an unexplained numeric literal other than 0 (zero) or 1 (one).
Remedy: Isolate a single copy of the number and refer to it. For example, isolate the number into:
- a local constant or enumerated type
- a global constant or enumerated type
- a constant class
- an initialisation file
Note: If your programming language does not support constants, simulate this—for example, by declaring a variable and initialising it at the beginning of the program.
References:
- The Pragmatic Programmer (Andrew Hunt, and David Thomas), 2000.
Research Findings:
-
Don't Repeat Yourself (DRY):
The DRY principle: Don't Repeat Yourself.