Code Comments
Comments capture intent, invariants, and non-obvious trade-offs. If the code can be clearer, prefer rename/refactor over a comment that restates the line.
When to comment
- Why a non-obvious approach was chosen
- Invariants and concurrency assumptions
- Workarounds for bugs in dependencies (link issue)
- Public API docstrings: params, returns, errors, examples
- Security-sensitive constraints
When not to
- Restate
i += 1as "increment i" - Leave stale comments that contradict code
- Joke or dead commented-out code blocks without reason
Rules
- Update comments in the same change as behavior.
- Prefer short, precise language; link specs when long.
- Public APIs get complete docstrings; internals only where needed.
- Mark TODOs with ticket refs if required by team norms — avoid empty TODOs.
- Do not invent library behavior in comments.
- For generated code, say so and point to source of generation.
Output format
Provide the commented code or a diff-style patch, plus a one-line rationale for non-obvious comments.
Edge cases
- Regulated code: traceability comments may be mandatory.
- Algorithms: complexity and references (paper/RFC).
- Deleted code: delete comments with code; use VCS history.