How To Write Clean Code Comments For Documentation (The Right Way)
Source: belikenative.com/write-clean-code-comments-documentation
I'll be honest: I've spent way too many hours staring at comments like "// increment i" or "// TODO: fix this later." We've all been there. Comments can either save your future self hours of head-scratching or turn your codebase into a cluttered mess. The trick is knowing when to write them, what to say, and how to keep them from becoming outdated.
Let me walk you through what actually works when documenting your code.
Why Most Comments Fail
The biggest mistake I see? Comments that explain *what* the code does instead of *why* it exists. If someone needs to understand what a loop does, they can read the code itself. That's the beauty of programming languages—they're already pretty readable if you write clean code.
But the *why*? That's gold. That's the context you'll forget three months from now when you're debugging at 2 AM.
Here's a real example from my own work:
```python
# Bad: explains the obvious
# Loop through all users and send emails for user in users: send_email(user)
# Good: explains the intent
# Send onboarding emails even if users haven't completed setup
# Some users skip the wizard, and we need them engaged for user in users: send_email(user) ```
See the difference? The bad comment is noise. The good one tells me *why* we're sending emails unconditionally, which might contradict what I'd expect.
Make Comments Self-Documenting (So You Need Fewer of Them)
Here's a counterintuitive tip: the best comment is often no comment at all. If your code needs a paragraph to explain what it does, maybe the code needs rewriting instead.
I'm not saying comments are bad. I'm saying clean, expressive code reduces your comment burden. Think of it this way: every comment is a liability. It needs to stay updated, stay relevant, and not mislead anyone.
When I write code, I ask myself: "Can I make this clearer by renaming a variable or extracting a method?" If yes, I do that first. Then I add comments only for the stuff that can't be expressed in code.
For example:
```javascript // Before: needs a comment // Calculate discount for returning customers who spent over $100 let d = 0; if (c.orders > 0 && c.total > 100) { d = 0.15; }
// After: self-documenting const RETURNING_CUSTOMER_DISCOUNT = 0.15; const MINIMUM_SPEND_FOR_DISCOUNT = 100;
let discount = 0; if (customer.hasPreviousOrders() && customer.totalSpend > MINIMUM_SPEND_FOR_DISCOUNT) { discount = RETURNING_CUSTOMER_DISCOUNT; } ```
The second version doesn't need a comment. The names tell the story. If you want to improve your writing skills—not just for code but for documentation in general—check out BeLikeNative. They focus on making your communication clearer, which is exactly what good commenting is about.
Stick to One Style (And Be Consistent)
Nothing drives me crazier than a file that mixes `//`, `/* */`, `#`, and `--` depending on the mood of whoever wrote it. Pick a style and stick with it across your project.
For most languages, the standard is:
- **Single-line comments** (`//` in JavaScript, `#` in Python) for brief explanations
- **Block comments** (`/* */` in C-style languages) for longer notes or disabling code
- **Doc comments** (`/** */` in Java/TypeScript, `"""` in Python) for formal API documentation
But honestly, consistency matters more than which style you pick. If your team uses `//` for everything, do that. Just don't switch mid-file.
I also recommend adding a comment header to each file or module explaining its purpose. Something like:
```python
# Module: payment_processor.py
# Handles all payment-related operations including validation,
# third-party API calls, and refund processing.
# See https://docs.example.com/payments for full documentation. ```
Short, sweet, and tells you exactly where to look for more info.
Keep Comments Current (Or Delete Them)
Outdated comments are worse than no comments. They actively mislead you. I've debugged issues for hours only to realize the comment explaining the "fix" was from a version three releases ago and no longer applies.
Here's my rule: when you change code, update the comments. If you can't update them, delete them. A missing comment is safer than a wrong one.
This is where version control helps. If you're wondering why something is done a certain way, `git blame` can tell you who wrote it and when. But that's a pain for every line. Good comments save you that step.
For a deeper dive into this exact topic—how to structure comments for documentation that people actually read—check out my guide on How To Write Clean Code Comments For Documentation. It covers patterns I've used across multiple projects.
Use Comments to Explain Constraints and Trade-offs
Some things can't be expressed in code. Business rules, performance constraints, workarounds for third-party bugs—these are perfect candidates for comments.
For example:
```java // We use a simple loop instead of Stream API here because // the list is always < 100 items, and Stream adds ~50ms overhead. // This buys us faster response times in batch processing. ```
Or:
```sql -- Using LEFT JOIN instead of INNER JOIN because some customers -- don't have orders yet, but we still need them in the export. ```
These comments explain *decisions*, not mechanics. That's the sweet spot.
I also like to mark workarounds with a clear label:
```python
# WORKAROUND: Third-party API returns 400 for valid requests
# if the timestamp is within 1 second of their clock.
# Add a 2-second delay to avoid this race condition. time.sleep(2) ```
When the third-party fixes their bug, this comment tells you exactly what to remove and why.
Avoid These Common Comment Pitfalls
Let me save you some pain. Here are the worst offenders:
- **The obvious:** "// This adds two numbers" — please don't.
- **The rant:** "// Don't touch this, it took me 3 days to figure out" — unprofessional and unhelpful.
- **The TODO graveyard:** "// TODO: refactor this mess" — if you're not going to do it, don't write it.
- **The novel:** A 50-line comment explaining a 5-line function — extract the explanation into a separate doc.
- **The lie:** A comment that contradicts the code — happens when someone changes code but not the comment.
If you find yourself writing any of these, stop. Take a breath. Either rewrite the code or delete the comment.
FAQ
**Q: Should I comment every function?** Only if the function's purpose isn't obvious from its name and parameters. Well-named functions like `calculateTotalWithTax()` usually don't need comments. Complex business logic might.
**Q: How do I handle comments that are out of date?** Delete them or update them immediately. Stale comments cause confusion. If you're not sure what the current code does, write a new comment that matches the behavior.
**Q: Can I use AI tools to write comments for me?** You can, but be careful. AI-generated comments often explain the obvious or miss the "why." Use them as a starting point, then edit for clarity and intent. If you want to polish your writing further, the BeLikeNative text simplifier can help you make sure your comments are easy to understand.
Final Thoughts
Clean comments are about communication, not decoration. They answer the "why" that your code can't. They stay concise, stay current, and respect the reader's time.
Next time you write a comment, ask yourself: "Will this help someone in six months?" If the answer is no, leave it out. If it's yes, make sure it's clear, consistent, and correct.
Your future self will thank you.
This article was originally published on belikenative.com/write-clean-code-comments-documentation.
BeLikeNative — free Chrome extension for grammar checking and writing improvement.