Recently I was doing a code review, and I stated that the person who was responsible for writing the code should remove the comments. They are too obvious I stated. The person was amazed that I was suggesting something which was the opposite of the encouraged software engineering “best practices”.

I proceeded to explain my philosophy on comments, and after a long and drawn out debate I think they came around. My philosophy goes like this. There are three types of comments:

  1. The Good
  2. These comments explain the reasoning behind your ideas at the time you wrote the code. They are the WHY comments. “We considered doing X but rejected it because of Y.” The because of Y is very important. In fact, that is what makes this a Why comment. We considered doing X but rejected it is a what comment and should be removed. If the reason Y (pun intended) can be called into question, then the code can be changed possibly for the better.

  3. The Bad
  4. As I hinted to above these are the WHAT comments. As an example “This loop checks each value in the array to see if it matches the given criteria”. Good naming should render this comment completely unnecessary. OK, but why take it out? Surely it isn’t hurting anything? No not right now, but it can easily get out of sync with the code, and end up confusing the heck out of somebody. Whereas if the variables are named correctly there is no need to explain what you have done, as it will be obvious by reading the code. If it is not obvious then simply refactor it into a method that explains what it is doing. For example the code that the comment described above could actually be factored into a method named CheckArrayForCriteria. Then it is obvious to everyone and there is no way the comment can later be rendered obsolete (and confusing) by a refactoring. Beside the fact that they can lie, there is another thing that I don’t like about what comments. They actually hinder your ability to read code. The eye is drawn to them, instead of the code itself. They also mess up what I call the visual locality of reference. They break up the code part above the comment from the code part below the comment, and if you read the comment, it may be difficult to remember the top part when considering the bottom part.

  5. The Ugly
  6. These are the bad comments that are sometimes a necessity if you are delivering an API to a third party. You don’t really want to write them, and more times than not they don’t add any value, but they are required and you can’t do a thing about it. These are the Javadoc or C# Xml (triple slash) comments. Yuck – they are hideous to look at, and completely destroy the visual locality of reference, but what can you do?