G8 Softwares / Naming And Reading

Comments Should Explain Why, Because The Code Already Says What

The reasoning behind a decision cannot be recovered by reading the decision.

A reader can always work out what the code does, given patience. It is right there, and it is the only account of itself that is guaranteed to be current. What a reader cannot recover, at any price, is why it does that rather than something else. Why the simpler approach was tried and abandoned. Why this ordering matters even though it looks arbitrary. Why a value that appears meaningless was chosen deliberately after a fault. That information exists only in someone's head on the day, and unless it is written down beside the code it evaporates, leaving behind something that looks like an accident and invites well meaning removal.

The most valuable comments are therefore historical and defensive. They record a constraint that is not visible locally: an external system that behaves badly under certain conditions, an ordering that a downstream consumer depends upon, a workaround retained because the obvious fix caused a worse problem elsewhere. Each of these protects a future reader from confidently making things worse. A comment that says a thing looks redundant but is not, and gives the reason, may be the single highest value line in a file, because it interrupts exactly the reasoning that would otherwise lead to a regression.

The corollary is that a comment restating the logic is not neutral. It costs attention on every read, and it will eventually contradict the code, at which point the reader must decide which to believe and has no basis for the decision. A stale comment is worse than none, because it actively misleads. The discipline is to delete freely when a comment merely narrates, and to write generously when you are about to leave a decision that will look strange later. If you find yourself thinking that a choice needs defending, that thought is the signal. Write the defence down while you still hold the reasons.