Magic Numbers/Strings
Unexplained literals in code.
“Avoid constants embedded in code.” – Robert C. Martin, Steve McConnell
Signs of Use (Symptoms)
- Numbers like
86400,3.14159,1000without explanation. - Strings like
"ADMIN","pending"scattered throughout.
Why it is bad (Consequences)
- Readability: What does
86400mean? - Maintainability: If the value changes, you must find all occurrences.
- Typo risk:
"penidng"vs"pending".
Why it happens (Root Cause)
Faster to just type the number than to define a constant.
When it might be okay (Exceptions)
- 0, 1 in obvious contexts (loop start, boolean).
- Mathematical constants where names don’t add clarity.
Explanation
Problem
setTimeout(fn, 86400000). What is 86400000?
The Flaw
It’s milliseconds in a day. But reader has to calculate. And if it’s wrong, no one notices.
Real world analogy
A recipe that says “bake at 423” instead of “bake at 425°F (220°C)”. Why 423?
Refactoring Solution
- Replace Magic Number with Symbolic Constant.
Pros and Cons (of the Antipattern)
| Pros (Why people do it) | Cons (The price you pay) |
|---|---|
Comparison
- Related Antipatterns: Uncommunicative Name.
- Related Principles: Readability.
Code example
Typescript
Bad (The Antipattern)
Good (The Fix)
PHP
Good (The Fix)