Chapter 17. Comment Only What the Code Cannot Say

Kevlin Henney

image with no caption

THE DIFFERENCE BETWEEN THEORY AND PRACTICE is greater in practice than it is in theory—an observation that certainly applies to comments. In theory, the general idea of commenting code sounds like a worthy one: offer the reader detail, an explanation of what’s going on. What could be more helpful than being helpful? In practice, however, comments often become a blight. As with any other form of writing, there is a skill to writing good comments. Much of the skill is in knowing when not to write them.

When code is ill-formed, compilers, interpreters, and other tools will be sure to object. If the code is in some way functionally incorrect, reviews, static analysis, tests, and day-to-day use in a production environment will flush most bugs out. But what about comments? In The Elements of Programming Style (Computing McGraw-Hill), Kernighan and Plauger note that “a comment is of zero (or negative) value if it is wrong.” And yet such comments often litter and survive in a codebase in a way that coding errors never could. They provide a constant source of distraction and misinformation, a subtle but constant drag on a programmer’s thinking.

What of comments that are not technically wrong, but add no value to the code? Such comments are noise. Comments that parrot the code offer nothing extra to the reader—stating ...

Get 97 Things Every Programmer Should Know now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.