Code comments matter because they preserve the reasoning a program cannot carry on its own: why a decision was made, what a non-obvious value means, what breaks if a piece of code changes, and what an outside system expects. The code tells the next reader what happens; a good comment tells them why it happens that way and what happens if they touch it. Write comments for intent, constraints, and hazards, not for restating syntax. The sections below cover which information belongs in a comment, which belongs in code instead, and how to keep comments from becoming a second bug list.

The subject is ordinary imperative code in a maintained codebase β€” not API documentation generators, commit messages, or architecture decision records, though each of those deserves separate treatment. Everything here assumes one condition: someone else, or you in eight months, will read this file without the conversation that produced it. That reader is the whole audience.

A quick boundary before the detail. A comment is a promise that the surrounding text stays true. Every comment you leave behind is a small maintenance debt, which is why the question is not "should I comment" but "which comments earn their place." The answer changes by language and toolchain, and that difference is where most advice falls apart.

Code States the Mechanics; a Comment Must Carry the Reason It Cannot Express

Start with the distinction that settles most arguments. A comment explaining what the next line does is usually noise, because the line already says it. A comment explaining why the line exists is usually valuable, because nothing in the syntax records it.

Take a retry loop with a three-second delay. The delay is visible. The reason it is three and not thirty β€” the upstream service times out at four seconds β€” exists only in the head of whoever tuned it. Six months later, someone "optimizes" the delay to thirty seconds and the integration starts failing under load with no obvious cause. The comment # upstream gateway times out at 4s; keep this under it costs one line and prevents that.

Tim Peters, one of the principal authors of Python, put the general principle in the Zen of Python as "Readability counts" and, in the same document, "Special cases aren't special enough to break the rules." That second line is a comment's real job: recording the exceptions. Code generalizes well and documents poorly, and every codebase accumulates decisions that are correct but not obvious.

A test to apply before typing //: try to write the comment as "this exists because…" If the sentence completes easily, the comment has value. If the only completion is "…this increments i," delete it. The corollary matters too β€” if the why is obvious from a well-named function, no comment is needed. Good naming is a comment that runs.

Four Kinds of Information Belong in a Comment and Nothing Else Does

The information worth writing splits cleanly into four buckets. Each answers a question the code cannot, and each maps to a specific failure when omitted.

Intent and rationale. Why this approach over the alternative. // Binary search because the list is sorted and grows to ~2M entries; linear scan measured at 400ms tells a future reader both the choice and the constraint that justifies it. Remove the benchmark figure and someone replaces it with a hash map "for speed."

Constraints and invariants. The conditions the code assumes: "argument must be pre-sorted," "caller holds the lock," "this runs only after migrations." These are the comments most likely to be missing and most expensive when absent, because a violated invariant produces a bug far from its cause.

Non-obvious values and magic numbers. A literal 86400 in a timeout means nothing until a comment says "one day in seconds." The number 100 is worse β€” it could be a percentage, a batch size, or a limit someone chose arbitrarily in 2019. Say which, and say who set it if it came from outside the team.

External contracts and hazards. Third-party quirks, protocol expectations, known bugs with workarounds, deprecated paths kept for compatibility. // Stripe webhook retries for 72h; idempotency key must persist 3 days is not decoration.

What does not belong: a changelog inside the file ("added 2024-03-12"), commented-out code kept "just in case" (version control remembers), and author tags that duplicate the blame log. If a comment's only content is a date and a name, delete it.

Comments Are Not the Same as Docstrings, Types, or Commit Messages

Readers routinely conflate four artifacts that serve different readers at different times. Getting the mapping right stops people from commenting where a better tool exists.

Artifact Primary reader Answers Toolchain that enforces it
Inline comment Maintainer editing this block Why this line/decision Nothing; review only
Docstring / doc comment Caller of the function What it does, params, returns, errors pydoc, Javadoc, JSDoc, rustdoc, Go doc
Type annotation Compiler and caller What shape the data has mypy, TypeScript compiler, Go compiler
Commit message Reviewer and future bisector Why this change landed now Git history, code review

The failure mode is using one artifact for another's job. A docstring that restates the signature (@param name the name) is pure maintenance cost β€” Javadoc's own style guidance discourages @param comments that merely repeat the parameter name. A type annotation does what a comment like // userId is a string never can: the compiler checks it.

Version-specific wrinkle worth knowing: Python's type hints became standard with PEP 484 in 2015, and since then a large class of # type: comments has been made obsolete by inline annotations. Go takes the opposite stance β€” go doc and godoc build documentation directly from comments placed above declarations, so a missing comment is a missing doc page, not a private note.

The practical rule: if a tool can enforce the fact, use the tool. If no tool can enforce it because it's a judgment, constraint, or history, that's exactly what a comment is for.

Seven Failure Modes Bad Comments Cause, from Stale Lies to Deleted "Obvious" Guards

Comments don't just fail to help; they actively cause harm. Here are the failure cases worth designing against.

Stale comments that contradict code. The comment says "returns null on failure," the code throws. A new developer writes a caller that checks for null, and the exception crashes production. The comment is worse than nothing because it was trusted.

Zombie commented-out code. Blocks of dead code accumulate because deleting feels risky. They bloat the file, confuse search-and-replace, and one day get un-commented by mistake during a merge.

Comments that override the code. This is the worst case: a fix gets applied but the "do not touch β€” see ticket #4412" note stays, and a future maintainer reverts the correct fix. Worse, a comment saying "this guard is unnecessary" can cause someone to remove a check that was protecting against a specific edge case documented nowhere else.

Redundant narration. i++; // increment i trains readers to skip comments entirely. Once skipping is a habit, the one comment that matters gets skipped too.

Misleading author blames and dates. // Fix by Alice, 2019 doesn't help unless Alice's change is the reason β€” and then the reason should be stated, not the name.

Over-commenting to compensate for bad naming. If you need a comment to explain what process2 does, rename it. A comment proves the naming failed.

The missing invariant. No comment at all where a constraint exists. The code looks correct in isolation; the constraint lives in a wiki page nobody reads after onboarding.

The common thread: a comment that is wrong is a liability, and a comment that is obvious is clutter. The only defensible comments are those that are both true and non-obvious, and both properties need active maintenance.

Nine Rules for Writing a Comment That Stays True

Here is a sequence for writing a comment that survives the next refactor. Apply it before committing.

1: State the why first. Open with the reason, not the mechanism. If you can't finish "this is here because…", skip the comment. 2: Name the constraint and its source. "Must be < 4s β€” gateway timeout per integration doc" beats "keep delay short." 3: Record the ticket or decision reference when the reason is external. // per ADR-0012 or // see #4412 turns a mystery into a trail. 4: Avoid restating the code. If the comment could be generated from the AST, delete it. 5: Prefer docstrings for public API, inline comments for local reasoning, and types for everything a type system can check. 6: Use a marker convention for debt. TODO(owner): and FIXME: are searchable; unstructured "hack" notes are not. Many teams standardize these in linters. 7: Write the comment you'd want to read at 2 a.m. during an incident. Terse, factual, pointing at the failure it prevents. 8: Update or delete on every change to the code it describes. A stale comment is a bug in review. 9: Skip the comment when the code is self-evident. Naming and structure are cheaper than maintenance.

Order matters here. Step 1 filters out 60% of would-be comments. Step 8 prevents the failure mode that makes people distrust comments in the first place.

How to Audit a Codebase for Missing or Misleading Comments

This is about triage. If you have a codebase full of comments and no idea which to trust, work in this order.

Start with the invariants. Grep for assert, if not, locks, and validation checks, and confirm each has a comment naming what it protects. Those are your highest-value read. Next, search for magic literals over 10 (timeouts, batch sizes, retry counts, percentages) and check each has a source. Third, review any comment that mentions a person's name, a date, or a ticket number β€” those tend to be the most stale. Fourth, run static analysis: tools like ESLint's no-warning-comments rule (in the ESLint rule set) can flag TODO and FIXME so they surface in CI, and SonarQube's issue tracker surfaces "commented-out code" smells.

For each flagged comment, apply a three-way decision: keep (non-obvious, true), rewrite (obvious but with a real reason buried in it), or delete (stale, redundant, or commented-out code). Most codebases have more of the third category than expected.

A useful measurement: track the ratio of comment deletions to additions over a sprint. A healthy codebase deletes about as many comments as it adds, because refactors invalidate them. A ratio near zero suggests comments are accumulating without upkeep.

Language and Tooling Change What a Comment Should Look Like

The same principle β€” record the why β€” produces different artifacts in different ecosystems, and getting this wrong wastes effort.

In Go, comments above exported declarations become the package documentation via go doc. That means a comment is not optional decoration; it's the public API surface. The Go project's own convention (golint historically, and community guidance) is that exported identifiers must be documented.

In Python, PEP 257 defines docstring conventions, and tools like Sphinx and pydoc render them. A # type: comment used to carry type info before PEP 484; now x: int = 0 is the standard, and type comments are reserved for legacy compatibility.

In Java, Javadoc comments are compiled into HTML and are expected on public methods. The Javadoc tool itself warns on malformed tags, which makes bad doc comments loud rather than silent.

In Rust, /// doc comments feed cargo doc, and //! documents the enclosing module β€” a distinction most languages don't make.

In JavaScript/TypeScript, JSDoc @param/@returns annotations are read by editors for autocomplete even without a type system. In .ts files, native types replace most JSDoc, and the JSdoc becomes redundant.

The takeaway: before writing a comment, know whether your toolchain will actually read it. A comment that lands only in the source file is a maintainer note; a comment that feeds a doc generator is a public contract. These deserve different rigor.

Where Comments Go Wrong Even When They Exist

Having comments is not the same as having helpful comments. A few edge cases trip up even experienced teams.

First, internationalized codebases. A comment in a developer's native language is unreadable to half the team and un-searchable in a mixed-language repo. Team convention usually favors the business language, and that should be documented.

Second, security-sensitive code. Comments describing an authentication check or cryptographic parameter can themselves be a leak if they name the specific vulnerability or bypass. Comment the invariant (e.g., "validate constant-time compare β€” see security review"), not the exploit.

Third, generated code. Files produced by protobuf, ORM migrations, or CSS preprocessors should either be marked // Code generated … DO NOT EDIT (the Go convention) or excluded from review, otherwise comments inside them become noise that nobody can safely change.

Fourth, performance-critical paths. A comment predicting a speedup is a promise that expires. Prefer "measured 400 ms for 2M rows on 2024 hardware" over "fast because it's hot path."

Fifth, and often missed: a comment that documents a temporary workaround needs an explicit removal condition. "Remove after the legacy API is retired" is a real comment; "temp hack" is a future bug.

How Teams Measure Whether Comments Are Working

The interesting question isn't whether comments exist β€” it's whether they help or harm. You can measure both.

The first proxy is review conversations about comments. If reviewers repeatedly ask "what does this mean?" or "why?" on a line, the comment (or the naming) failed. If reviewers delete comments in review, that's healthy β€” likely redundant ones.

The second is searchability. Run a grep for TODO, FIXME, HACK, XXX. Each marker should point to an owner and a condition. A codebase with hundreds of TODOs and zero resolution dates is documenting debt it never plans to pay.

Third, onboarding time. Time how long a new engineer needs to safely change a core module. If the answer is "weeks," look at whether invariants are documented. The comment isn't a magic wand; it's a signal that non-obvious reasoning exists and is written down.

Fourth, incident postmortems. When a production bug traces to a misunderstood constraint, the fix is usually a comment added where the misunderstanding occurred. Postmortems surface the missing comment β€” the one that would have prevented it β€” more reliably than any code review.

A stable target most teams settle on: high-value comments on invariants, public API, and external constraints; zero tolerance for stale or commented-out comments; and a steady delete-to-add ratio that shows the codebase is being pruned.

FAQ

Are comments actually necessary if the code is self-documenting?

Self-documenting code covers what and rarely why, so the test is whether a decision needs the reason attached. A well-named function with clear types needs no comment on the happy path, but the reason for a peculiar cutoff, retry budget, or ordering usually lives outside syntax. Teams that rely on naming alone tend to lose the constraints the code depends on, and those constraints surface during incidents rather than code review. Comment the reason; rename the rest.

Do too many comments make code harder to read?

Yes, when the comments restate mechanics, because readers start skipping them and then skip the ones that matter too. The usable signal is a comment that a teammate could not reconstruct by reading the code alone. Crowding comments with anything obvious β€” variable names, loop counters, increments β€” undermines the trust that a good comment depends on. Write fewer, sharper comments and delete the obvious ones outright.

A comment says a function returns null on failure but the code throws. Which is right?

The code runs; the comment does not, so trust the code and treat the comment as a defect in the change that altered behaviour. The dangerous part is that a caller may still be checking for null because the comment said so, which is a latent crash. The fix is to update the comment in the same commit that changed the return behaviour, and to add a regression test if a downstream caller depended on the old contract. A stale comment is precisely the failure case a review process exists to catch.

Where should the rationale for a design choice go β€” in the file, the commit message, or a separate document?

Put the local, code-level reason inline where the choice applies, so a reader editing the block sees it without hunting. Put the cross-cutting, historical reason in the commit message or an ADR, because commit messages follow the code as a searchable record, whereas a code comment can become stale as surrounding lines move. A short pointer like "see ADR-0012" bridges the two. If the reason affects many files, a document is the correct home and the comment only needs to point at it.

Are TODO and FIXME comments a sign of poor quality?

They're a sign of undeclared debt, not necessarily poor quality. Teams that run static analysis β€” ESLint's no-warning-comments rule surfaces them β€” can attach them to owners and dates, which turns informal notes into tracked work. The unhealthy version is a codebase with thousands of free-floating TODOs and no plans to resolve any; that's a signal that debt is documented but unpaid.

Does the comment-to-code ratio say anything useful?

Only loosely, and only within a codebase, because the ratio is highly language-specific: a Javadoc-heavy Java codebase naturally has more comments per line than a typed Python or Rust codebase, where types and doc comments absorb most of the exposition. The useful measure is the trend: whether the team deletes roughly as many comments as it adds during refactors, which indicates the comments are being kept honest. A ratio that only ever grows suggests the comments are accumulating without upkeep.

Can a comment describe a security check or password handling without becoming a security risk itself?

Yes, if it describes the invariant or the intent rather than a bypass. "Constant-time compare; validate on review" is safer than naming the specific vulnerability bypass, which a reader with a public repo can see. When in doubt, put the specific reasoning in a private ticket and leave the comment as a pointer. That keeps the code reviewable without turning the source file into a partial disclosure.

This article is general educational information about software engineering practice, not a compliance or security recommendation. Code review, security, and organizational policy requirements vary by jurisdiction, employer, and toolchain; consult your team's engineering standards or a qualified security professional before relying on any convention described here.