I was listening to a podcast recently and one of the hosts made a comment that I’ve heard before. “There are two types of comments – lying and useless.”
For the most part, it’s a fair point. When people comment for the sake of commenting, we end up with useless comments – those that simply repeat the obvious. In the following example, the comment doesn’t add to the user’s understanding and in fact makes the code harder to read:
DateTime admissionDate = new DateTime(year, month, day); // a date
In this case, because the variable is descriptively named, the code is self-documenting; the urge to comment here would suggest that the variable name needs to be updated.
Similarly, a comment that describes how a function works is in danger of becoming outdated the next time the function is updated, if the developer doesn’t notice and update the comment as well. This leads to confusion as the comment no longer accurately describes the functionality. In this case, it’s worth looking at whether we can refactor the code to be more clear so that it doesn’t need a comment.
What I take issue with is the suggestion that these are the only kinds of comments; I actually find comments to be useful in a variety of situations. Here are some times I use comments:
- Explaining the why
- For a while, I had an extra line of code that worked around an outstanding issue I needed another team to fix. A comment explained why the line was there and when it could be removed (with a link to the issue that needed to be fixed)
- XML comments
- I wrote a function recently where a particular option should be used only in certain situations, where it didn’t make sense to include the entire situation in the variable name. An XML comment on the function helped make sure it was used correctly; the next time I referred to it the intellisense helped me set the parameters correctly.
- SVN comments
- This one might be cheating a bit, since it’s not strictly a code comment…but when trying to find one particular change among many commits (when I don’t know exactly where the change is), having descriptive svn comments is a huge help.
Self-documenting code (in particular, good naming) and version control (no need to leave large blocks of code commented out when you can simply retrieve them later if needed) greatly reduce the need for comments, but don’t remove it entirely. Your code should show intent – that is, what you want to do. Let your comments show motivation – why you’re doing it.