Prof. Stearns
Magic Numbers as Defined by Prof. Stearns (and many professionals)
A magic number is a literal constant (numeric or text) in your source code or comments that exhibits one
or more of the following characteristics.
Such constants are
not acceptable in professional code.
The magic number principles apply to code and comments; a magic number
in a comment causes the same problems as one in code.
- It is possible the number may require changing in the future;
the change could stem from new requirements, design changes, or code rewrites.
- Another computer professional, who generally understands the program,
cannot immediately determine the meaning of the constant.
- The number will change if the code is moved to a different
platform (not applicable in Java). For example:
ASCII to EBCDIC problem
different integer size
endian switch
Notes and suggestions
- A good comment often solves the understandability problem.
(But never if the magic # is in two or more places!)
- Use a well-commented constant for values
that may change; put the constant in an appropriate place where
the programmer can find it.
- Use of a constant may not eliminate the magic number; X is
still a magic number.
final int X=235;
- Use metadata for constants that may change due to a platform change.
- Use metadata for all parameters that need to be changed by the user.
Last updated on 1/1/06