As a general principle, I don’t like comments in source code. It’s not that I consider them onerous to write, I just don’t think that they’re very useful, for three reasons:
- They’re not synchronised with the code they describe, and their accuracy can deteriorate over time.
- They’re often a substitute for clearly-structured code
- They make source code longer, which can obscure the underlying logical flow.
That may sound controversial to some people: extensive commenting is still in some quarters considered an essential discipline of computer programming. But I use modern, expressive programming languages that allow me to communicate a lot more in the code itself.
Here’s a good Ruby example I encountered earlier in the week (I’ve broken the second line to make it readable on the site):
# pick the lowest total entries pager.total_entries = kittens.total_entries > puppies.total_entries ? kittens.total_entries : puppies.total_entries
You might legitimately ask why the comment’s there at all. It’s not as if it tells us anything we couldn’t work out by reading the second line, right?
Except … the second line is a bit long, and actually needs a bit of thought to decipher it—and when we do so carefully, we find that the code is doing the opposite of what the comment says: it’s finding the highest total entries.
It turns out that the code is right, and the comment’s wrong—we might have expected that, because there are tests to ensure that the code does what it’s supposed to. So what’s the comment doing, again, except for misleading us?
There’s no blame to be apportioned here—this is a natural consequence of trying to explain a long line of code—but we can improve it. Instead of using a comment to explain what’s going on in this line, we can get Ruby to do it for us:
pager.total_entries = [kittens.total_entries, puppies.total_entries].max
In less space than the original, that clearly conveys that we are choosing the maximum of two values. There was nothing wrong with the original code, it’s just that our programming language has a better way of doing it.
It’s a trivial example, but a good principle: use descriptive code instead of comments. The desire to add a comment is often a good indicator that the code itself can be made clearer. By choosing good variable names, extracting functional chunks of code into clearly-named methods, and taking advantage of language features, comments become mostly superfluous.
There is still a place for comments: sometimes, a program has to do something counter-intuitive that can’t be explained by the code. But these cases are relatively rare.