
Navigating the Art and Science of Code Comments
Indrajeet Patil

Source code: github.com/IndrajeetPatil/to-comment-or-not
🎯 Goal
Learning to write comments that clarify intent, not echo code.
Despite Python examples, all the mentioned strategies are language-agnostic.
None of this advice is dogma; there can be valid reasons and conventions to break these rules.
- Boswell & Foucher
Good comments act as guideposts for navigating complex code.
Multiple pressures during development make thoughtful commenting difficult.

def is_valid_email(email: str) -> bool:
“““Check if email address is valid.
Args:
email: Email address to validate
Returns:
True if valid, False otherwise
“““
# RFC 5322 simplified: local@domain format
local_part = r’[a-zA-Z0-9._%+-]+’
domain = r’[a-zA-Z0-9.-]+’
tld = r’[a-zA-Z]{2,}’
pattern = rf‘^{local_part}@domain.{tld}$’
return re.match(pattern, email) is not None
Documentation
Comments
Every comment distracts from reading code—make sure it’s worth the interruption.
Fix the unclear code instead: \(good code > bad code + comments\).
Don’t duplicate the code in comments
Why not ‘Don’t state the obvious?’
Obvious depends on your audience. Code clear to senior developers may confuse juniors.
Consider team experience when deciding what needs explanation.
Don’t write non-local comments
Don’t retain dead code as comments
Don’t narrate git history
Exception: Bundled/distributed code without git access may need key change notes in comments.
Don’t confuse docs with comments
Don’t write mandated comments
Arbitrary rules like “one comment per 10 lines” or “every function must have a comment” lead to noise, not clarity.
Write comments when they add value, not to meet quotas.

Source: Geek & Poke
Don’t write confusing comments
Bad comments are worse than no comments. They mislead readers and create confusion.
Whatever helps the reader understand the code more easily: the what, the why, the how

Your future self as the reader
Good comments explain business logic, design decisions, and non-obvious requirements.
✅ Comments explain rationale
Complex logic benefits from explanation—even when developers could eventually figure it out.
When you intentionally deviate from language conventions, explain why the idiomatic approach doesn’t work and preempt questions.
It’s acceptable to document known issues, limitations, or future improvements using action comments.
Common Action Comment Tags
| Tag | Purpose | Example |
|---|---|---|
TODO |
Planned improvement or missing feature | # TODO: Add caching (issue #123) |
FIXME |
Known bug that needs fixing | # FIXME: Fails on negative input (#456) |
HACK |
Temporary workaround for a problem | # HACK: API bug workaround (ticket #789) |
NOTE |
Important clarification or caveat | # NOTE: Must run before init() |
OPTIMIZE |
Performance improvement opportunity | # OPTIMIZE: Use binary search (#234) |
Tip: Use the Better Comments VS Code extension to highlight these tags in your editor.
Well-chosen examples often clarify complex code more effectively than detailed comments alone.
Credit original sources
Credit the source when adapting code from elsewhere, which also provides context for future maintainers.
Link to external references
When implementing specs, algorithms, or standards, provide references where readers can learn more.
Cautionary comments prevent well-intentioned “fixes” that break subtle constraints by warning against seemingly obvious “improvements”.
Security comments prevent dangerous “simplifications” that introduce vulnerabilities by explaining why “obvious” optimizations break security boundaries.
Concurrency comments prevent race conditions from “optimizations” that remove checks by explaining locking order, invariants, and why seemingly redundant logic matters.
Refactoring to “simplify” ↓
When a function is legitimately complex and shouldn’t be broken down further, use comments to delineate logical sections.
Note: Refactoring into smaller functions is still preferable unless there’s a strong reason (tight I/O coupling, measured performance need, transaction boundaries).
Use section comments to:
Keep them precise and compact.
Use information-dense words
Avoid pronouns
Explain intent, not implementation
Keep comments updated
Use specific references
Maintain professional tone
Stay objective
Avoid inside jokes
Avoid editing banner comments
While content matters most, consistent formatting improves readability.
Proper indentation
Vertically align end-of-line comments
Block comments with breathing room
Consistent capitalization
Consistent punctuation
Tip: Configure your linter/formatter to enforce these aesthetic choices consistently.
“Code never lies, comments sometimes do.”
— Ron Jeffries
What tools CAN do:
What they CANNOT do:
The fundamental limitation
Tools can enforce format but not value. Good commenting requires human judgment about what information is helpful.
Why AI tools can help:

LLM-Generated Comments
LLMs can overcomment or generate redundant comments, but they can also tighten verbose ones.
Always review LLM-generated comments critically.

Fresh eyes catch what you miss: outdated comments, missing context, and unclear intent!
“Good code is its own best documentation.”
— Steve McConnell
When encountering unclear code, prioritize refactoring over commenting. Only add comments for inherently non-obvious logic.

“Don’t comment bad code — rewrite it.”
— Kernighan & Plaugher
Applying the decision workflow: refactor first, comment only what remains non-obvious.
❌ Poor naming + excessive comments
Transformation: Renamed function/variables + Pythonic idiom → eliminated 6 redundant comments. Added 1 comment explaining non-obvious business decision (>= vs >).
Well-written comments make complex code comprehensible.
Writing thoughtful comments forces you to articulate your reasoning and design decisions, improving code quality.
Good comments preserve business knowledge and domain expertise for future developers.
Consistent commenting practices reduce cognitive overload and make maintenance safer.

Invest time in thoughtful comments early—practice makes perfect.
And Happy Commenting! 😊
Check out my other slide decks on software development best practices
Syntax varies by language; the distinction is universal.
| Language | Documentation | Comment | Documentation Tools |
|---|---|---|---|
| Python | """docstring""" |
# comment |
Sphinx, pdoc |
| JavaScript | /** JSDoc */ |
// comment |
JSDoc, TypeDoc |
| TypeScript | /** JSDoc */ |
// comment |
TypeDoc, TSDoc |
| Java | /** Javadoc */ |
// comment |
Javadoc |
| Kotlin | /** KDoc */ |
// comment |
Dokka |
| C | /** Doxygen */ |
/* comment */ |
Doxygen |
| C++ | /** Doxygen */ |
// comment |
Doxygen |
| Go | // Doc comment |
// comment |
godoc, pkgsite |
| Rust | /// Doc comment |
// comment |
rustdoc |
| Swift | /// Doc comment |
// comment |
DocC |
| R | #' Roxygen |
# comment |
roxygen2 |
| C# | /// XML Doc |
// comment |
DocFX, Sandcastle |
| PHP | /** PHPDoc */ |
// comment |
phpDocumentor |
| Ruby | # YARD comment |
# comment |
YARD, RDoc |
For a more detailed discussion about how to comment, see the following references:
Kernighan, B. W., & Plauger, P. J. (1978). The Elements of Programming Style (2nd ed.). McGraw-Hill. (pp. 117-128)
McConnell, S. (2004). Code Complete (2nd ed.). Microsoft Press. (pp. 777-818)
Boswell, D., & Foucher, T. (2011). The Art of Readable Code. O’Reilly Media, Inc. (pp. 45-65)
Martin, R. C. (2009). Clean Code. Pearson Education. (pp. 53-74)
Goodliffe, P. (2007). Code Craft. No Starch Press. (pp. 73-88)
Contieri, M. (2023). Clean Code Cookbook. O’Reilly Media, Inc. (pp. 111-121)
Gregg, E. (2021). Best practices for writing code comments