Editorial note: I originally wrote this post for the NDepend blog. You can check out the original here, at their site. While you’re there, take a look at all of the visualizations and metrics that you can get about your codebase.
Given that I both consult and do a number of public things (like blogging), I field a lot of questions. As a result, the subject of code comments comes up from time to time. I’ll offer my take on the correct way to comment code. But remember that I am a consultant, so I always have a knee-jerk response to say that it depends.
Before we get to my take, though, let’s go watch programmers do what we love to do on subjects like this: argue angrily. On the subject of comments, programmers seem to fall roughly into two camps. These include the “clean code needs no comments” camp and the “professionalism means commenting” camp. To wit:
Chances are, if you need to comment then something needs to be refactored. If that which needs to be refactored is not under your control then the comment is warranted.
And then, on the other side:
If you’re seriously questioning the value of writing comments, then I’d have to include you in the group of “junior programmers,” too. Comments are absolutely crucial.
Things would probably go downhill from there fast, except that people curate Stack Overflow against overt squabbling.
Splitting the Difference on Commenting
Whenever two sides entrench on a matter, diplomats of the community seek to find common ground. When it comes to code comments, this generally takes the form of adages about expressing the why in comments. For example, consider this pithy rule of thumb from the Stack Overflow thread.
Good programmers comment their code.
Great programmers tell you why a particular implementation was chosen.
Master programmers tell you why other implementations were not chosen.
When you’ve rewritten, refactored, and rearchitected your code a dozen times to make it easy for your fellow developers to read and understand — when you can’t possibly imagine any conceivable way your code could be changed to become more straightforward and obvious — then, and only then, should you feel compelled to add a comment explaining what your code does.
Junior developers rely on comments to tell the story when they should be relying on the code to tell the story.
And so, as with any middle ground compromise, both entrenched sides have something to like (and hate). Thus, you might say that whatever consensus exists among programmers, it leans toward a “correct way” that involves commenting about why.