Writing Effective Comments
You'll learn how to write comments that genuinely help readers understand your code's reasoning without stating the obvious.
The Core Idea
A good comment explains why something exists, not what it does. Your code already shows what happens—comments should reveal intent, justify trade-offs, or warn about non-obvious constraints. Think of comments as footnotes in a textbook: they provide context the main text can't easily convey.
What Makes Comments Effective
Explain Intent and Rationale
Comments shine when they reveal decisions: "Using binary search here because the dataset averages 10,000+ items" tells readers why you chose that approach.
Document Non-Obvious Behavior
If something looks wrong but is actually correct, explain it: "Off-by-one is intentional—API expects exclusive end index." This prevents well-meaning colleagues from "fixing" correct code.
Highlight Trade-offs
When you sacrifice readability for performance or vice versa, say so: "Nested loop is O(n²) but n is always < 20, so clarity wins over optimization."
What to Avoid
Don't Describe Obvious Code
Bad: // increment counter before counter = counter + 1
The code is self-evident; the comment adds no value.
Keep Comments Accurate
Outdated comments are worse than no comments—they mislead. If you refactor code, update its comments immediately.
Don't Use Comments to Fix Bad Naming
If you need a comment to explain a variable, rename the variable instead. Comments should supplement good names, not replace them.
The Analogy
Think of comments as GPS directions for a road trip. Don't say "turn the steering wheel left"—the driver can see that. Instead, explain "take this detour because the bridge ahead is under construction." Reveal what isn't obvious from the road itself.
Key Takeaway: Write comments that explain why, document surprises, and justify decisions—not comments that just translate code into English.