literals with no name and no explanation
Magic Numbers
Bare literals -- 86400, 0.0825, 200, "admin" -- force the reader to reconstruct intent and scatter a value across the codebase with no single place to change it.
A number the reader has to decode is a comment you forgot to write.
01in the wild
In the wild
Name the Intent
A literal with no name. The reader has to guess what 86400 or 0.0825 means.
example.js
// SMELL: what is 86400? why 0.0825? why 3?
if (now - created > 86400) expire();
const total = price * 1.0825;
if (retries > 3) giveUp();
// RIGHT: name the intent
const SECONDS_PER_DAY = 86_400;
const SALES_TAX = 0.0825;
const MAX_RETRIES = 3;
if (now - created > SECONDS_PER_DAY) expire();A named constant documents the value and gives it one place to change. The number stops being a riddle.
// observed
magic: reader greps for 86400 across the repo named: SECONDS_PER_DAY reads itself
Status Codes & Thresholds
Bare codes and limits live only in the author's head; enums make the legal set explicit.
example.java
// SMELL: 200, 404, 7 -- meaning lives only in your head
if (status == 200) ok();
if (daysOpen > 7) escalate();
// RIGHT: enums and named constants
if (status == HttpStatus.OK) ok();
static final int ESCALATION_THRESHOLD_DAYS = 7;
if (daysOpen > ESCALATION_THRESHOLD_DAYS) escalate();Enums and constants make illegal values harder to write and legal ones self-explaining.
// observed
magic: 200 could be anything enum: HttpStatus.OK is unambiguous
Magic Strings Too
A literal string is a magic number in disguise -- invisible to the type checker, easy to mistype.
example.py
# SMELL: bare strings are magic numbers in disguise
if user.role == "admin": # typo "Admin" silently denies
grant()
# RIGHT: a named enum the type checker can police
class Role(str, Enum):
ADMIN = "admin"
if user.role == Role.ADMIN:
grant()A literal string is as magic as a literal number: the type checker can't see it and a typo fails silently. An enum names the legal set.
// observed
string: 'Admin' != 'admin', silent deny enum: one canonical value
02weakness catalog
Mapped weaknesses (CWE)
On its own, this defect is catalogued by MITRE as one or more of these weaknesses. The exploitable vulnerability usually appears only when it chains or combines with another.