Sunday 31 August 2003 — This is close to 20 years old. Be careful.
There’s a thread going around about comments in source code. Christian said:
Not all comments are bad. But they are generally deodorant; they cover up mistakes in the code. Each time a comment is written to explain what the code is doing, the code should be re-written to be more clean and self explanatory.
Comments are an escape hatch for expressing everything about the program that the programming language can’t.
Opening shots notwithstanding, the essays agree more than they disagree. Both decide that there are lots of important uses for comments. In my experience, it boils down to a simple distinction:
Code says what to do, comments say why.
The comments Christian is railing about in his post are probably comments that tell you what is happening. We’ve all seen the classic:
i++; // increment i
This is bad because the code already described what is happening, and the comment is simply describing it again. No new information has been added to the system. Of course in the real world, the examples are usually not so blatant.
If you find yourself writing comments that describe the “what”, think about whether you have an expressive-enough coding style, or whether you need richer primitives, or a more directly applicable framework. There may be ways to change your coding so that the “what” is adequately covered by the code. Then you can focus on the “why” in your comments.
BTW: Christian also covers the writer’s difficulty of understanding their audience from a commenter’s point of view in his followup post.
I guess the basic tenet that code should be the "what" and comments the "why", but even that assumes that the "what" may be obvious. Most of the time, yes, but sometimes even the what of what is happening must be explained, since some kinds of code are too densely packed for clarity, yet serve a need which should not be compromised due to a distaste for comments.
Kernighan & Plauger's "Elements of Programming Style," 1974, said something to the effect, "Comments are an apology for bad code."
Also, in addition to the why, comments should also say why not! I.e., if your first read of the API documentation suggested that you might be able to write the code one way, but you found out along the way that there were complications so you had to do it another way, you should comment not just what you did, but what you didn't do and why you didn't do it!
I also like to use "headers" for each sub / function / whatever within a larger app that details dependencies and what-have-you.
Add a comment: