Skip to content

Writing better comments

↑

Good comments preserve information that the code alone does not clearly show. They explain why a decision exists, which invariants must be preserved, what outside system imposes a constraint, or how a non-obvious edge case should behave. They should not narrate every line of syntax.

Unhelpful:

// Increase attempts by 1.
attempts++;

The comment merely translates the line into English. A better method name or expression would be enough.

Better:

// The remote service rejects retries after the lease expires.
if (leaseMillisecondsRemaining > retryDelayMilliseconds)
ScheduleRetry();

This gives a reason, but only if the claimed lease behavior is real and verified.

Best for an important invariant:

// Inventory IDs come from the server; never allocate a new ID during reconnect.
// Reusing IDs prevents duplicated items when a reconnect message is repeated.
MergeServerInventory(snapshot);

The important design rule is not obvious from the method call, and a reviewer can check that tests preserve it.

  • Use a descriptive identifier rather than a comment explaining an obscure abbreviation.
  • Delete obsolete commented-out code; Git history already records earlier implementations.
  • Do not put passwords, production addresses, tokens or personal data into comments.
  • Avoid permanent TODO comments that have no clear owner or action. Prefer a tracked issue for work that matters to the team.
  • Update or remove a comment when code or assumptions change. Incorrect comments can be worse than missing ones.
// O(1) expected lookup with a well-distributed hash; worst-case behavior differs.
return inventoryById.TryGetValue(id, out item);

A statement such as // always O(1) would overclaim. The correct comment names the assumption. Even technically accurate claims should be included only when they help someone understand a relevant decision.

Ask whether a future reader can identify the reason, whether the comment is still true, and whether a test could enforce the invariant. Comments are for human understanding; C# XML documentation is particularly useful for public contracts.