Replace Magic Numbers with Named Constants
What you'll learn: How to turn cryptic hard-coded values into self-documenting named constants that make your code maintainable.
The Problem with Magic Numbers
A "magic number" is any hard-coded literal value in your code whose meaning isn't immediately obvious. When you see if (status == 3) or timeout = 5000, you're left wondering: What does 3 mean? Why 5000?
These mystery values create several problems:
- Unclear intent: Future readers (including yourself) must guess what the number represents
- Duplication: The same value scattered across files makes updates error-prone
- No type safety:
3could mean "approved status" in one place and "retry count" in another
The Solution: Named Constants
Replace each magic number with a descriptive constant defined once:
# Before: magic number
if (status == 3):
process_payment()
# After: named constant
APPROVED_STATUS = 3
if (status == APPROVED_STATUS):
process_payment()
Now the code reads like English. The number 3 has context and meaning.
When to Extract Constants
Look for:
- Numeric literals that aren't self-evident (
86400is seconds-per-day, not obvious) - Repeated values used in multiple places
- Configuration values like timeouts, limits, or thresholds
- Status codes or enumerated values
Don't extract truly obvious values like 0 for array initialization or 1 for simple increments.
Think of It Like This
Imagine reading a recipe that says "bake for 72 units." Units of what? Compare to "bake for MINUTES_FOR_GOLDEN_CRUST = 72." Constants are labels on your ingredients.
Key Takeaway: Replace hard-coded numbers with descriptive named constants to make your code self-documenting, reduce duplication, and prevent errors when values need to change.