Skip to content
All essays
CraftMarch 27, 20257 min

Code Comments: When and How to Use Them

Master the art of code comments. Learn when to comment, when to refactor, and how to write clear documentation.

Ü
Ümit Uz
Mobile & Full Stack Developer

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 case

Clarify 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 bug

Warnings

typescript
// WARNING: This function is deprecated. Use newFunction() instead.
// Will be removed in v2.0

Best Practices

  1. 1Keep comments current
  2. 2Use consistent style
  3. 3Don't use comments to explain bad code
  4. 4Document public APIs
  5. 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!

Enjoyed this essay? Share it.

Related essays

Next essay
Naming Conventions: Write Self-Documenting Code