I remember my C++ teacher arguing strongly that all code should be commented and you should never hesitate to add comments. "When in doubt: comment!". I did not agree with him then, and I do not agree with him now. With experience, I have come to realize that comments in high level language code is rarely needed. I won't go so far as to say that writing comments are a failure, but its pretty close.
Readable code is self-documenting code!
A comment followed by a block of code can often be replaced by a method which states the intent just as well as the comment, and makes the code more modular and reusable.
- It makes refactoring happen more often.
- It helps us write readable code. Readable code is a joy to work with.
- It tends to make methods short and sweet.
- It avoids comments getting out of sync with the code
- It challenges you to rewrite commented code that is hard to understand.
Apart from the cleanliness of the code, there are a number of others problem with having comments in the code as well. Number one problem being that comments does not automatically change with the code. You end up with comments that disagrees with the actual program, which leads you on a wild goose chase spending lots of energy trying to figure out what is going on. I rarely read in-line comments for this reason and when I do, I always have to assume they are wrong.
Note that I am talking about in-line comments primarily. There are situations where comments have its uses. For example, to provide an overview of a class or module, to reference external documentation or maybe to explain the rationale for a workaround in the code.
When I see comments in code, I think of them as personal challenges:
Can I remove that comment and make the code more readable?
Try it yourself next time!
Here are some mostly real life examples of comment problems I've come across. I used these snippets in a code quality workshop I ran for a client: