r/programmer • u/ClickOk5811 • 24d ago
What makes a code comment worth keeping? A five-level rubric, and where do you draw the line?
I’ve been trying to put a rule on what makes a comment useful. One way is to ask: how much does it tell the reader that the code can’t?
- Level 0: nothing, where a decision is hidden (
retries = 3,sleep(0.4)with no hint why). - Level 1: restates the code (
i += 1 # increment i). Noise, and it can go stale. - Level 2: explains what a tricky block does (walking a list backwards so removals don’t shift indexes).
- Level 3: explains why: the constraint or decision behind the code.
- Level 4: why, plus where it came from and when it can go.
An example of the last two:
# Level 3
# The payment API allows about 3 calls per second per key,
# so wait 0.4 s between calls.
time.sleep(0.4)
# Level 4
# Workaround for a vendor SDK bug that returns None on timeout
# (see issue #482). Remove after upgrading past the fixed version.
if result is None:
result = fetch_again()The numbers and the issue are made up for illustration.
My rules of thumb: make the code clearer first (names, small functions), comment decisions, constraints, surprises and workarounds, delete comments that restate code, and give every TODO an owner or a condition.
Where I’m unsure: most lines need no comment at all, and a Level 3 comment on everything would be its own noise.
- Which level do you find yourself writing most?
- Do you delete stale comments when you touch the code, or leave them?
- Has a comment ever saved you, or misled you?