Video in progress

When are comments in code useful, and when do they become a code smell?

A comment is useful when it answers "why": a business reason, a bug being worked around, a non-obvious decision. When the comment explains "what the code does", that usually means the code itself is unclear, and you should fix it with a name or by extracting a method.

📖 Answer

A needless comment:

// check the user's age
if (u.getAge() >= 18 && u.getStatus() == 2) { ... }

The comment repeats the code, and status == 2 is still unclear. Better:

if (user.isAdult() && user.isVerified()) { ... }

A useful comment:

// The bank API returns the old rate between 00:00 and 00:15 (ticket BANK-412),
// so during this window we use the cached rate.
if (isBankMaintenanceWindow(now)) return cachedRate;

You can't read this from the code; it is context.

The main risk of comments is that they go stale. The code changes, the comment stays and now lies, and the compiler doesn't check it. So:

  • commented-out code: delete it, it is in the git history;
  • // TODO: with a ticket number or not at all;
  • Javadoc for public APIs: write the contract (does it return null, which exceptions), not the implementation.

A practical test: can you delete the comment and put a well-named method or variable in its place? If you can, do it.