Clean Code: To Comment or Not to Comment

Ah, comments. The good, the bad, and the ugly. We've all seen them. While good comments can be a lifesaver, bad comments are worse than no comments at all. The best-case scenario? Your code is so clear it doesn't even need comments. But when you do need them, make sure they explain the 'why', not the 'what'.

Here are a few examples in TypeScript.

Explain "Why", Not "What"

Your code should already explain what it's doing. Your comments should explain the reason behind it.

// Bad: This comment explains WHAT the code is doing.
// Checks if the user is a student or a senior
if (user.isStudent || user.age > 65) {
  applyDiscount(user)
}

// Good: This comment explains WHY the code is there.
// We offer discounts to students and seniors to make our services more accessible.
if (user.isStudent || user.age > 65) {
  applyDiscount(user)
}

Don't Comment Bad Code, Rewrite It

Commenting on confusing code is like putting a band-aid on a broken leg. The better solution is to refactor the code to be clearer.

// Bad: A comment is used to clarify confusing code.
// Checks if the user has a blue-level subscription and has been active in the last 30 days
if (user.subscription.level === 'blue' && user.lastActive < 30) {
    // ...
}


// Good: The code is rewritten to be self-documenting.
const isBlueLevelSubscriber = user.subscription.level === 'blue';
const isActiveInLast30Days = user.lastActive < 30;

if (isBlueLevelSubscriber && isActiveInLast30Days) {
    // ...
}

When Comments Are Useful

Sometimes, comments are necessary, especially for complex logic that can't be simplified further.

// Good: A comment explaining a complex regular expression.
// This regex matches a valid email address format. It's not exhaustive,
// but it covers the most common use cases.
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
  // ... handle invalid email
}

Tips

  • Your code should be the single source of truth. Comments can get out of date.
  • Before writing a comment, see if you can make the code itself more expressive.
  • When you do write comments, make them count. Explain the intent and the reasoning.