Code Smells
16 min
A code smell isn't a bug — the code runs fine — but it's a signal that something about the design will likely cause pain later. A magic number is a classic one: an unexplained numeric literal buried in the middle of logic, with no indication of what it means or why that specific value was chosen.
def has_magic_number(code_values, allowed):
return any(v not in allowed for v in code_values)
# 86400 shows up with no explanation -- what IS 86400?
print(has_magic_number([0, 1, 86400], {0, 1})) # True -- flagged
86400 is the number of seconds in a day — obvious once you know that,
completely opaque otherwise. SECONDS_PER_DAY = 86400 fixes it
immediately: now the constant explains itself everywhere it's used.
Both functions compute the exact same thing -- but only the second one tells you WHY '30' and '5' matter, and only the second one is safe to change (rename GRACE_PERIOD_DAYS's value once, instead of hunting for every '30' that might or might not mean 'grace period').
Duplicated code is another classic smell — the same logic copy-pasted in multiple places means every future bugfix or change has to be applied EVERYWHERE it was copied, and it's easy to miss a spot:
from collections import Counter
def count_duplicate_lines(lines):
counts = Counter(lines)
return sum(1 for line, c in counts.items() if c > 1)
code = ["x = compute_total()", "y = 2", "x = compute_total()"]
print(count_duplicate_lines(code)) # 1 -- that line appears twice
The fix for duplication is usually extraction: pull the repeated logic into its own function, called from every place that needs it — exactly the single-responsibility principle from the previous module, applied to eliminate the duplication rather than just tolerate it.
Write `has_magic_number(code_values, allowed)`: given a list of numeric literals found in some code and a set of self-explanatory `allowed` values (like `{0, 1}`), return True if any value ISN'T in `allowed` — a 'magic number' that should probably be a named constant.
Write `count_duplicate_lines(lines)`: given a list of code lines, return how many DISTINCT lines appear more than once — a simple proxy for duplicated logic.
What is a 'code smell'?
You can identify magic numbers and duplicated code as code smells, and know the standard fix for each (named constants; extraction into a shared function).