Skip to content
Velloreth
Programming 8 min read

When to Write Code Comments (and When Not To)

Comments explain why, not what. Learn which comments earn their place, which are noise, and how to write ones that stay accurate.

By

The core rule

Comments should explain why, not what.

The code already says what it does. A comment that repeats it adds a line to read and maintain without adding information.

// Bad: restates the code
// Increment the counter by one
counter++;

// Good: explains why
// Retry once because the upstream service occasionally returns a stale cache
counter++;

The first comment is noise. The second tells you something the code cannot.

Comments that are a smell

A comment that exists because the code is unclear is a signal to fix the code.

// Bad: the comment compensates for unclear code
// Check if the user is eligible: they must be over 18, in the US,
// not banned, and verified
if (u.a >= 18 && u.c === 'US' && !u.b && u.v) { }

The fix is not a better comment. It is a better expression:

// Good: the code says it
const isEligible = user.age >= 18
  && user.country === 'US'
  && !user.isBanned
  && user.isVerified;

if (isEligible) { }

Now no comment is needed. The names carry the meaning.

The general principle: when you feel the urge to write a comment explaining what a block does, extract the block into a function with a name that says it instead.

Comments that earn their place

Explaining intent

Why this approach, rather than the obvious one.

// We sort by id rather than timestamp because timestamps can collide
// when records are inserted in the same millisecond.
records.sort((a, b) => a.id - b.id);

The code shows the sort. The comment explains why this key.

Documenting constraints

Non-obvious limits imposed by an external system.

// The API rejects payloads over 1 MB, so we chunk at 900 KB to leave
// room for the envelope.
const CHUNK_SIZE = 900 * 1024;

Without the comment, a future reader might “optimise” the chunk size and break the integration.

Recording workarounds

A hack that exists for a reason.

// Safari 17 does not fire the transitionend event when the element is
// hidden, so we use a timeout as a fallback. Remove when Safari 18 ships.
setTimeout(onTransitionEnd, 300);

The comment explains the workaround and when it can be removed. Without it, someone will delete the timeout and reintroduce the bug.

Warning about consequences

// WARNING: this mutates the input array. Callers must pass a copy.
function sortInPlace(items: Item[]): Item[] { }

The signature does not show the mutation. The comment does.

Linking to context

// See https://github.com/org/repo/issues/1234 for the full discussion
// of why we chose this approach.

A link to the issue or design document gives the reader the full reasoning without duplicating it.

Explaining a non-obvious algorithm

// Floyd's tortoise and hare: the fast pointer moves twice as fast, so if
// there is a cycle they must eventually meet.
while (fast && fast.next) {
  slow = slow.next;
  fast = fast.next.next;
  if (slow === fast) return true;
}

The algorithm is not obvious from the code. Naming it lets the reader look it up.

Comments that do not

Restating the code.

// Bad
i++; // increment i

Explaining the obvious.

// Bad
// Loop over the users
for (const user of users) { }

Commented-out code.

// Bad
// const oldTotal = items.reduce((a, b) => a + b.price, 0);
const total = items.reduce((a, b) => a + b.price * b.qty, 0);

Version control remembers deleted code. Commented-out code accumulates and confuses.

Journal comments.

// Bad
// 2026-01-15: added validation - Ada
// 2026-02-03: fixed bug with empty input - Grace

Git blame does this better.

Attribution.

// Bad
// Written by Ada

Git does this.

Stale comments. The worst kind, because they actively mislead.

// Bad: the code no longer does this
// Returns null if the user is not found
function getUser(id: string): User {
  return db.find(id) ?? createGuestUser(); // returns a guest, not null
}

A reader trusting the comment will write code that breaks.

Doc comments

Doc comments on public APIs are a different category. They describe the contract, not the implementation.

/**
 * Calculates the total price of a cart, including tax and discounts.
 *
 * @param cart - The cart to total. Must have at least one item.
 * @param options - Optional overrides for tax rate and currency.
 * @returns The total in the smallest currency unit (cents).
 * @throws {EmptyCartError} If the cart has no items.
 * @throws {InvalidCurrencyError} If the currency is not supported.
 *
 * @example
 * const total = calculateTotal(cart, { currency: 'USD' });
 */
function calculateTotal(cart: Cart, options?: TotalOptions): number { }

A good doc comment answers:

  • What does this do?
  • What are the parameters, and what are their constraints?
  • What does it return?
  • What can it throw?
  • Does it have side effects?
  • Is there an example?

It does not describe the implementation. That is what the code is for.

Comments versus other tools

Before writing a comment, consider whether another tool does the job better.

NeedBetter tool
Explain what code doesA better name or an extracted function
Explain a decisionA design document or an ADR
Track changesGit history
Enforce a ruleA linter
Describe a public APIA doc comment or generated docs
Explain a workaroundA comment, with a link to the issue

Comments are the right tool for the last row, and for intent that cannot be expressed in code.

Keeping comments accurate

A stale comment is worse than no comment. Two habits help.

Keep comments close to the code. A comment immediately above the line it describes is more likely to be updated than one at the top of the file.

Treat comment updates as part of the change. When you modify code, check whether the nearby comments still hold. Reviewers should flag stale comments as blocking.

Prefer comments that cannot go stale. A comment explaining why a decision was made stays true even as the code changes. A comment describing what the code does goes stale immediately.

Comments in configuration and infrastructure

The same rules apply outside application code, and the stakes are often higher because configuration is read by people who did not write it and cannot easily test a change.

A comment in a CI workflow explaining why a step exists prevents someone from deleting it as redundant:

# Pinned to 3.11 because 3.12 changed the default hash algorithm and
# broke our cache keys. Revisit when the cache layer is updated.
- uses: actions/setup-python@v5
  with:
    python-version: '3.11'

A comment in a Terraform or Kubernetes file explaining a non-obvious setting prevents a well-meaning “cleanup”:

# The health check timeout is deliberately long: the service warms a
# large in-memory index on first request, which takes ~40s.
health_check_timeout = 60

These are exactly the comments that earn their place. The value is not obvious from the code, the reason is not recoverable from the surrounding context, and removing the line would cause a subtle failure. Without the comment, the next person sees an odd number and “fixes” it.

The failure mode is the same as in application code: a comment that restates the configuration adds nothing, and a stale comment about a setting that has since changed is actively harmful.

Practical guidance

  • Comment the why, not the what.
  • If a comment explains what the code does, refactor instead.
  • Document intent, constraints, workarounds, and non-obvious decisions.
  • Never leave commented-out code — delete it.
  • Write doc comments for public APIs, describing the contract.
  • Keep comments close to the code they describe.
  • Update comments as part of the change, and flag stale ones in review.
  • Prefer a better name over a comment whenever the name can carry the meaning.

For the related practices, see naming conventions guide and writing clean functions. For the broader context, refactoring basics and code review checklist.

Quotable summary

Comments should explain why, not what, because the code already says what it does and a comment repeating it adds noise. A comment that exists because the code is unclear is a signal to refactor the code rather than document the confusion. Comments earn their place when they explain intent, document constraints, record workarounds, warn about consequences, or link to context. Stale comments are worse than no comments because they actively mislead, so keep them close to the code and update them as part of any change. Doc comments on public APIs are a separate category and should describe the contract — parameters, return value, errors, and side effects — rather than the implementation.

Frequently asked questions

Should I comment my code?
Comment the why, not the what. If a reader can see what the code does, a comment repeating it is noise. If the reason for the code is not obvious, a comment explaining it is valuable.
What is the difference between a good and a bad comment?
A good comment explains intent, a constraint, or a non-obvious decision. A bad comment restates the code, is out of date, or exists to compensate for unclear code that should be refactored.
Are comments a code smell?
Not inherently. A comment explaining why a workaround exists is valuable. A comment explaining what a confusing block does is a smell, because the block should be made clear instead.
How do I keep comments up to date?
Keep them close to the code they describe, and treat updating them as part of any change. A comment far from the code it explains will drift. Reviewers should flag stale comments.
What should a doc comment contain?
For a public API: what the function does, its parameters, its return value, the errors it can throw, and any side effects. It describes the contract, not the implementation.
Should I comment out code instead of deleting it?
No. Version control remembers deleted code. Commented-out code accumulates, confuses readers, and is never cleaned up. Delete it and rely on git history.