The Comment Dilemma
Comments are a double-edged sword. Good comments clarify intent; bad comments mislead and become obsolete.
typescript
// Bad: Commenting bad code
// Check if user is admin
if (user.role === 'admin') { }
// Good: Self-documenting code
if (user.isAdmin()) { }When to Comment
Explain Why, Not What
typescript
// Bad: Says what
// Increment counter
count++;
// Good: Explains why
// Backoff retry to avoid overwhelming the server
const delay = Math.pow(2, attemptCount) * 1000;Document Decisions
typescript
// Chose Bloom filter over hash set because:
// - Memory efficient (1M items vs 10MB vs 40MB)
// - O(1) lookup time
// - Acceptable false positive rate for this use caseClarify Complex Logic
typescript
// Calculate days between dates accounting for:
// - Leap years
// - Different month lengths
// - Timezone differences
const daysDiff = calculateBusinessDays(start, end);When NOT to Comment
Don't Comment Obvious Code
typescript
// Bad
// Set variable to 5
const five = 5;
// Good
const MAX_RETRIES = 5;Don't Comment Instead of Refactoring
typescript
// Bad
// Check if user is logged in and has permission
if (user && user.isLoggedIn && user.permissions.includes('edit')) { }
// Good
if (user.canEdit()) { }Comment Types
JSDoc
typescript
/**
* Creates a new user account
* @param email - User's email address
* @param password - User's password (min 8 chars)
* @returns The created user object
* @throws {ValidationError} If validation fails
*/
async function createUser(email: string, password: string): Promise<User> {
validateEmail(email);
validatePassword(password);
return db.insert('users', { email, hash: hash(password) });
}TODO/FIXME
typescript
// TODO: Add rate limiting (ticket #123)
// FIXME: This fails for edge case X
// HACK: Temporary workaround for API bugWarnings
typescript
// WARNING: This function is deprecated. Use newFunction() instead.
// Will be removed in v2.0Best Practices
- 1Keep comments current
- 2Use consistent style
- 3Don't use comments to explain bad code
- 4Document public APIs
- 5Explain non-obvious requirements
Conclusion
Good comments explain "why," not "what." Prefer self-documenting code over comments, but use comments to clarify intent, document decisions, and warn about pitfalls.
Write comments that add value!