Script Valley
Writing Technical Documentation
Code Comments and Inline DocumentationLesson 5.1

When to comment code and when not to

good vs bad comments, comment anti-patterns, self-documenting code, naming as documentation, explaining why not what, redundant comments, comment maintenance

When to Comment Code

When to Comment Code

The worst comment explains what code does. The best comment explains why code does it. If you need a comment to explain what a line does, the code should be rewritten. Comments that describe mechanics add maintenance burden without adding value.

Comment the Why

// BAD β€” explains the what (obvious from the code)
// Increment the counter
counter++;

// GOOD β€” explains the why (not obvious from the code)
// Rate limiter uses a sliding window; increment before checking
// so the current request counts against the limit
counter++;

When to Always Comment

  • Non-obvious side effects β€” If calling this function changes state elsewhere
  • Workarounds β€” Bug number, ticket link, and why the workaround is necessary
  • Business rules β€” Logic that comes from requirements, not technical necessity
  • Performance trade-offs β€” Why a less-readable approach was chosen for speed

Self-Documenting Code First

Before adding a comment, ask: can I rename this variable or function to make the comment unnecessary? A function named calculateMonthlyInterestWithCompounding() needs fewer comments than calc(). Good naming is better than good commenting.

Up next

Writing JSDoc comments for JavaScript functions

Sign in to track progress

When to comment code and when not to β€” Code Comments and Inline Documentation β€” Writing Technical Documentation β€” Script Valley β€” Script Valley