Comments: When Write When Delete
Learn: Comments: When Write When Delete
Welcome to TopperBlog! 👋
I'm a tech content creator passionate about helping developers level up their careers and master cutting-edge technologies.
🎯 What I Write About:
• AI/ML Engineering & LLMs
• Web3 & Blockchain Development
• System Design & Architecture
• Interview Preparation (FAANG)
• Freelancing & Remote Work
• Modern Tech Stacks (Next.js, React, Rust, TypeScript)
• Performance Optimization & Best Practices
💼 Mission: Sharing practical, actionable insights that accelerate your tech career and maximize your earning potential.
📚 15+ In-Depth Guides covering everything from earning $10k/month as a freelancer to cracking FAANG interviews.
🌐 Let's connect and grow together in this amazing tech journey!
#TechBlogger #SoftwareEngineering #CareerGrowth #WebDevelopment #AIEngineering
1500W Fun: Comments
Hook
Ever stared at code you wrote six months ago and thought, "What was I thinking?" Comments are your time machine—but only if they're actually useful. Let's write comments that make future-you smile instead of cry.
Story
I once inherited a codebase where every function had comments like:
// increment i
i++;
Meanwhile, the actual logic—a Byzantine algorithm for calculating optimal cache invalidation—had nothing. The code was self-documenting in the worst way: it documented the obvious and hid the important.
That's when I learned: comments aren't for explaining what code does; they're for explaining why it does it.
The When, Where, Why
✅ WRITE Comments When:
1. The "Why" Isn't Obvious
// We sort by creation date DESC, not modification date, because
// users expect to see their most recent uploads first. Modification
// date changes when we auto-optimize images, which breaks UX.
const sorted = items.sort((a, b) => b.createdAt - a.createdAt);
2. You're Doing Something Counterintuitive
// Intentionally using loose equality here. The API returns "1" (string)
// for true and "0" for false. Strict equality would break legacy clients.
if (response.isActive == true) {
// ...
}
3. There's a Gotcha or Limitation
// WARNING: This regex doesn't handle nested parentheses.
// For that, we'd need a proper parser. See issue #4521.
const pattern = /\([^)]*\)/g;
4. You're Working Around a Bug
// Chrome 89 has a memory leak with ResizeObserver.
// Remove this workaround once we drop support for Chrome <90.
// Tracked in: https://bugs.chromium.org/p/chromium/issues/detail?id=1234567
observer.disconnect();
observer = null;
5. Performance Matters and It's Not Obvious
// Using Set instead of Array.includes() for O(1) lookup.
// With 10k+ items, this reduces search time from 50ms to <1ms.
const validIds = new Set(allowedIds);
6. You're Making a Deliberate Trade-off
// Caching aggressively here (24 hours) even though data might be stale.
// The performance gain is worth occasional inconsistency for this use case.
// See performance analysis: docs/caching-strategy.md
cache.set(key, value, { ttl: 86400 });
❌ DELETE Comments When:
1. The Code Is Self-Explanatory
// ❌ BAD
const age = currentYear - birthYear; // calculate age
// ✅ GOOD
const age = currentYear - birthYear;
2. The Comment Just Repeats the Code
// ❌ BAD
// Check if user is admin
if (user.role === 'admin') {
// ✅ GOOD
if (user.role === 'admin') {
3. The Comment Is Outdated
// ❌ BAD
// This used to be slow, but we optimized it in v2.1
const result = fastAlgorithm();
// ✅ GOOD
const result = fastAlgorithm();
4. The Comment Contradicts the Code
// ❌ BAD
// Returns true if user is inactive
return user.isActive; // This is confusing!
// ✅ GOOD
return user.isActive;
5. You're Commenting Out Code
// ❌ BAD
// const oldApproach = calculateTax(income);
// const newApproach = calculateTaxV2(income);
const result = newApproach;
// ✅ GOOD
// Use git history. Delete dead code.
const result = calculateTaxV2(income);
Code Examples: The Good Stuff
Example 1: Complex Algorithm
/**
* Calculates the Levenshtein distance between two strings.
*
* Used for fuzzy search matching. We chose this over Jaro-Winkler
* because it's more intuitive for users and performs better on
* our typical query lengths (5-20 chars).
*
* Time: O(m*n) | Space: O(m*n)
*
* @param {string} a
* @param {string} b
* @returns {number} edit distance
*/
function levenshteinDistance(a, b) {
const matrix = Array(b.length + 1)
.fill(null)
.map(() => Array(a.length + 1).fill(0));
// Initialize first row and column
for (let i = 0; i <= a.length; i++) matrix[0][i] = i;
for (let j = 0; j <= b.length; j++) matrix[j][0] = j;
// Fill matrix
for (let j = 1; j <= b.length; j++) {
for (let i = 1; i <= a.length; i++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
matrix[j][i] = Math.min(
matrix[j][i - 1] + 1, // deletion
matrix[j - 1][i] + 1, // insertion
matrix[j - 1][i - 1] + cost // substitution
);
}
}
return matrix[b.length][a.length];
}
Example 2: Business Logic
function calculateDiscount(orderTotal, customerTier) {
// Premium tier gets 15% off, but only on orders over $100.
// This threshold was set by marketing to encourage larger purchases.
// See: https://notion.so/pricing-strategy-2024
if (customerTier === 'premium' && orderTotal > 100) {
return orderTotal * 0.15;
}
// Standard tier gets 5% off, no minimum.
if (customerTier === 'standard') {
return orderTotal * 0.05;
}
return 0;
}
Example 3: Workaround
function fetchUserData(userId) {
// The API sometimes returns 500 errors during their 2-3 AM maintenance window.
// We retry with exponential backoff instead of failing immediately.
// This is temporary until they implement proper graceful degradation.
// TODO: Remove this in Q3 2024 when they upgrade their infrastructure.
return retryWithBackoff(() => api.get(`/users/${userId}`), {
maxAttempts: 3,
baseDelay: 1000,
});
}
Tips for Comment Mastery
| Tip | Example |
| Use "Why" not "What" | ❌ "Loop through items" → ✅ "Sort by date DESC for chronological feed" |
| Link to context | Add issue numbers, docs, or design decisions |
| Flag future work | Use TODO, FIXME, HACK, XXX with context |
| Document assumptions | "Assumes input is always valid JSON" |
| Explain trade-offs | "We chose X over Y because..." |
| Keep them close | Comments above the code they describe |
| Update with code | If you change logic, update the comment |
| Use JSDoc for APIs | Public functions deserve formal documentation |
| Be conversational | Write like you're explaining to a colleague |
| Avoid humor that ages | Memes and jokes become cringe in 6 months |
The Golden Rule
A comment should answer: "Why is this here, and why this way?"
If the code answers that question, delete the comment. If it doesn't, write one.
Future-you will thank you. 🚀