Comments: When and How to Use Them
What you'll learn: You'll discover when comments genuinely improve code versus when they signal that your code needs refactoring for better clarity.
The Core Principle
Comments are like training wheels on a bicycle—sometimes necessary, but ideally your code should be self-explanatory enough that they're rarely needed. A well-named function with clear parameters often communicates intent better than poorly written code with explanatory comments.
When Comments Add Value
Good uses:
- Why, not what: Explain why a non-obvious decision was made, not what the code does
- Business rules: Document external requirements or regulations that aren't obvious from code
- Warnings: Alert maintainers about gotchas or performance implications
- API documentation: Public interfaces benefit from structured documentation
When Comments Indicate Problems
Red flags:
- Explaining confusing logic: If you need comments to clarify what code does, refactor it with better names instead
- Apologizing for bad code: Comments like "// hack" or "// fix this later" mean you should fix it now
- Outdated information: Comments that contradict the code are worse than no comments
- Obvious statements:
// increment counterabovecounter++adds noise, not value
The Refactoring Alternative
Instead of commenting complex logic, extract it into a well-named function. Compare:
// Calculate employee bonus based on tenure and performance
bonus = (years * 1000) + (rating * 500);
versus:
bonus = calculateEmployeeBonus(yearsOfService, performanceRating);
The second needs no comment—the function name is the documentation.
Key Takeaway: Comments should explain why decisions were made, not what code does—if you're explaining what, refactor your code to be self-documenting with meaningful names and clear structure instead.