A short word about comments in code

hieroglyphs

A common fallacy is to assume authors of incomprehensible code will be able to express themselves clearly in comments.

— Kevlin Henney

I quite like Kevlin Henney, particularly his talks. Some people grumble about his information density being a little bit low, (as if optimizing for information density is a good proxy for optimizing for information transfer – it’s not), but I find his talks both informative and entertaining. Above all though, I find them accessible. Kevlin spends a lot of time talking about is the mindset of clean code, which we’ll briefly encounter today.

A quote that strikes close to home is the one above. The typical knee-jerk reaction I experience when pointing out confusing code to newer programmers is something like, “Oh don’t worry, I added a comment to explain what I’m doing”. I used to trust that this would address the issue. But, on multiple occasions, you’ll revisit the code a couple weeks later. And, encountering said comment, you realize in dismay that it’s not only still confusing, but also incorrect.

The reason is a fairly logical too. In order to describe something clearly, you need to be able to reason about it clearly. Incomprehensible code is difficult to reason about. And therefore the comment, which is supposed to provide some insight, ends up being just as incomprehensible as the code.

Garbage in, garbage out, as data scientists love to say.

When someone is confused by a piece of code you’ve written, your first instinct should be to try and refactor the code in a cleaner way that’s easier to reason about. Not to put a top hat on a turd by adding a comment. Ideally, your code should be self-documenting (a la Clean Code, et al.), with comments being a last resort, such as when there’s a very particular reason you’re not pursuing the obvious solution.

After all, comments don’t get checked by the compiler, and don’t throw runtime errors if they’re incorrect. But they will cause you to reason incorrectly about code that’s difficult to reason about.