Nate Meyvis

A use of code comments

One sometimes hears that comments should be unnecessary, because properly written code tells you as much, and as clearly, as comments. Now, (i) sometimes our code is not perfect, and comments help in those times, and (ii) sometimes our teammates are more comfortable reading natural language than code. But here's another reason to use comments:

You should call things according to what they are, not what they do. But in context, the reader will want to know what they are doing, not just what they are. Comments are almost always better than temporary variables for this, and they're much better than giving the original object a worse name.

Suppose, for example, that you like to name prototypes after birds.1 You have a project-naming tool that calls a function, retrieveBirdNames, that retrieves a list of bird names from an API. (Pretend that it takes these names, filters out any that are already used or on a denylist, and returns a few random elements from what remains.)

How do you tell the reader of the code that the function of retrieveBirdNames is to give possible prototype names? Some options:

  1. Use a comment.
  2. Rename retrieveBirdNames to retrievePrototypeNameCandidates.
  3. Write another function, retrievePrototypeNameCandidates, that calls into retrieveBirdNames.
  4. Assign the result of retrieveBirdNames to a variable called prototypeNameCandidates.

(2) is dangerous and causes a lot of problems (especially if you don't add some explanation inside that function, in which case you've just moved, not eliminated, a necessary explanation). (3) might not be too bad, but bloats your code. (4) is usually not harmful, especially with modern optimizing compilers and interpreters, but it can cause technical debt and in the best case is a sort of comment that happens also to be code.

That leaves (1). Just add a comment! Keep names for what things are and use comments when you need also to tell the reader what they are doing.


  1. By the way, this Wikipedia category is delightful. (Here is a list of things named after partridges.)

#software