Comments

One of the perennial programmer arguments—not quite up there with Emacs v. Vim but enduring nonetheless—is whether or not we should comment our code and if so, how. some folks say that the need for comments is a code smell: an indication that the programmer did not write the code clearly enough. If the code is clear and well-structured, they say, there is no need for comments.

I’ve been doing this long enough to know the truth of this bit of programmer wisdom. Sometimes I’m lazy and don’t adequately comment. I’m always sorry later. Nate Finch has an interesting post that claims this is always true. For everyone.

Finch says that except for trivial examples there are no bad comments. Some may be superfluous but even in that case they don’t really hurt anything and are certainly better than not commenting at all. At the other end of the spectrum, Finch says that the most useful comments are the “why” comments. These are the comments that tell the reader why you’re doing what you’re doing. They’re important because they capture domain knowledge that’s not implicit in the code itself.

In the comments (heh), John Martin observes that the ideal of self-documenting code is never realized in practice. Except, again, in trivial cases I think that’s true. This bit of Elisp:

(defun add-a-to-b (a b)
  (+ a b))

could, I suppose, be called self-documenting but any serious piece of code is unlikely to be so.

So the TL;DR for this post is: I agree with Finch. Comment your code.

UPDATE [2017-12-23 Sat 15:13]:

I was rereading this post and noticed that my example of “self-documenting” code inadvertently made the Martin’s larger point. I intentionally wrote it to be so obvious that no comments were needed but on rereading it I realized that I chose a misleading name, add-a-to-b. That name suggests something like \(b \leftarrow a + b\), which is not, of course, what the code does. So it turns out that writing self-documenting code even in trivial cases isn’t that easy.

This entry was posted in Programming and tagged . Bookmark the permalink.