Home Knowledge Base Magic Number Detection

Magic Number Detection is the automated identification of literal numeric constants and undocumented string literals hardcoded directly in program logic — detecting the code smell where values like 86400, 3.14159, 0x1F4, or "application/json" appear without explanation in conditional checks, calculations, or configuration, forcing every reader to reverse-engineer the meaning and every maintainer to hunt down every occurrence when the value needs to change.

What Is a Magic Number?

A magic number is any literal value whose meaning is not self-evident from context:

Why Magic Number Detection Matters

Detection Rules

Standard linting configurations flag:

Legitimate Exceptions

Refactoring Pattern

# Before: Magic Number
if user.age < 18:          # Why 18?
    redirect("parental_consent")
if account.balance < 500:  # Why 500? USD? Cents?
    charge_fee(25)          # Why 25?

# After: Named Constants
MINIMUM_AGE_FOR_CONSENT = 18
MINIMUM_BALANCE_FOR_FREE_TIER_USD = 500
BELOW_MINIMUM_BALANCE_FEE_USD = 25

if user.age < MINIMUM_AGE_FOR_CONSENT:
    redirect("parental_consent")
if account.balance < MINIMUM_BALANCE_FOR_FREE_TIER_USD:
    charge_fee(BELOW_MINIMUM_BALANCE_FEE_USD)

Tools

Magic Number Detection is demanding context for every literal — enforcing the discipline that values embedded in logic must be named, documented, and centralized, transforming implicit business rules embedded in code into explicit, locatable, maintainable constants that every reader can understand and every maintainer can change safely.

magic number detectioncode ai

Explore 500+ Semiconductor & AI Topics

From EUV lithography to CUDA optimization — search the full knowledge base or chat with our AI assistant.