
Why Your Code Needs Comments (And How to Write Good Ones)
We’ve all been there. It’s 2 AM. Your eyes are burning from staring at the screen for hours. You’re digging through code you wrote six months ago, desperately trying to find why your application is crashing in production. And then it hits you: “What the heck was I thinking when I wrote this?”
Welcome to the nightmare that is uncommented code. Let’s talk about why comments matter and how to write ones that don’t suck.
Why Comments Are Non-Negotiable
1. Future You Will Thank You
The number one person who benefits from your comments is you. Sure, that algorithm makes perfect sense right now. But give it three months, two project switches, and a vacation, and you’ll be staring at your own code like it’s written in hieroglyphics.
# DON'T DO THIS:
x = (a + b) * (c / d) - (e * f)
# DO THIS INSTEAD:
# Calculate adjusted profit margin using the Henderson formula
adjusted_profit_margin = (revenue + subsidies) * (market_share / total_addressable_market) - (overhead * risk_factor)
2. Your Team Won’t Plot Your Murder
Every developer has a story about inheriting a codebase with zero comments. It usually ends with them questioning their career choices. Good comments are an act of compassion toward your colleagues.
3. Code Tells “How,” Comments Tell “Why”
Even the cleanest, most self-documenting code can only tell you how it’s doing something. Comments explain why you’re doing it that way, especially when the solution isn’t obvious.
// Had to use setTimeout with 0ms delay to fix event bubbling issue in IE11
// See bug #4328 for more details
setTimeout(() => {
processEvent(event);
}, 0);
The Art of Writing Comments That Actually Help
1. Comment on the “Why,” Not the “What”
Bad comment:
// Increment i by 1
i++;
Good comment:
// Skip the header row of the CSV
i++;
2. Document Assumptions and Edge Cases
Your code might rely on certain conditions being true. Document them!
// This function assumes input array is sorted.
// If unsorted, results will be incorrect and runtime will increase to O(n²)
int binarySearch(int arr[], int target) {
// ...
}
3. Warn About Dragons
If there’s a part of your code that’s particularly tricky or has known issues, leave a warning.
# WARNING: This API has rate limiting. Calls will fail if more than
# 100 requests are made within 60 seconds.
def fetch_user_data(user_id):
# ...
4. Don’t State the Obvious
Comments should provide value. If your code is clear enough that the comment is redundant, skip it.
// BAD:
// Define a variable called name
const name = "John";
// GOOD:
// Store user's display name (not their legal name) for UI presentation
const name = "John";
5. Keep Comments Up to Date
Outdated comments are worse than no comments at all. They actively mislead readers.
# DANGEROUS:
# Returns user ID as an integer
def get_user_id(): # Function was changed to return a string instead
return str(user.id)
6. Use Block Comments for Complex Logic
For complex algorithms or business logic, a block comment explaining the overall approach is invaluable.
/**
* Calculates shipping cost based on:
* - Package weight (with oversize penalties)
* - Destination zone (international needs customs processing)
* - Delivery speed (express vs standard)
* - Current fuel surcharges
*
* Business rule: We round up to nearest dollar for display, but store
* exact amount for accounting.
*/
function calculateShippingCost(package, destination, speed) {
// ...
}
Commenting Different Types of Code
API Documentation
If you’re writing public APIs, thorough documentation is non-negotiable. Use JSDoc, Javadoc, or similar standards:
/**
* Authenticates a user against the database
*
* @param {string} username - The user's login name
* @param {string} password - The user's plaintext password (will be hashed)
* @returns {Promise<Object>} User data object if successful, null if authentication failed
* @throws {DatabaseError} If database connection fails
*
* @example
* const user = await authenticate('johndoe', 'securepassword123');
* if (user) {
* console.log(`Logged in as ${user.displayName}`);
* }
*/
async function authenticate(username, password) {
// ...
}
Configuration Files
Comment your configuration settings, especially if they’re not self-explanatory:
# Maximum number of concurrent connections
# Setting too high can exhaust server resources
max_connections: 100
# Controls how aggressively invalid sessions are purged
# 0 = never, 1 = hourly, 2 = daily, 3 = weekly
session_cleanup: 2
CSS Comments
CSS deserves comments too, especially for hacks or browser-specific workarounds:
/* Fix for Safari rendering bug - don't remove unless tested in Safari */
.container {
transform: translateZ(0);
}
/* Mobile layout breaks at exactly 768px */
@media (max-width: 767px) {
/* ... */
}
When Comments Become a Code Smell
If you find yourself writing extensive comments to explain what your code is doing, it might be a sign that your code needs refactoring.
// BAD: Needs a comment to explain what it does
// This function checks if user is premium, has active subscription,
// hasn't exceeded quota, and has permission for this resource
function canUserAccess(user, resource) {
return user.type === 'premium' && user.subscriptionStatus === 'active'
&& user.quotaUsed < user.quotaLimit && hasPermission(user, resource);
}
// BETTER: Self-documenting and needs minimal comments
function canUserAccess(user, resource) {
return isPremiumUser(user)
&& hasActiveSubscription(user)
&& isWithinQuota(user)
&& hasPermission(user, resource);
}
Automate When Possible
Consider tools that help with documentation:
- Documentation generators (JSDoc, Sphinx, Javadoc)
- Linters that check for missing docstrings
- IDE plugins that generate comment templates
- Pre-commit hooks to enforce documentation standards
Conclusion
Comments are like insurance for your code. They might seem like unnecessary overhead when you’re rushing to meet a deadline, but you’ll be grateful for them when things inevitably break down.
Remember:
- Write comments for humans, not machines
- Focus on explaining why, not what
- Keep them concise, accurate, and up-to-date
- Use them to complement good code, not excuse bad code
The best code is a perfect balance of self-documenting structure and strategically placed comments. Your future self and colleagues will thank you for taking the time to document your code properly.
Now go forth and comment your code. Because the person who has to debug it at 2 AM might be you.