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
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.
