| Robert C. Martin's Clean Code book has a great section on comments: - The proper use of comments is to compensate for our failure to express ourself in code. Comments are always failures. We must have them because we cannot always figure out how to express ourselves without them, but their use is not a cause for celebration. So when you find yourself in a position where you need to write a comment, think it through and see whether there isn’t some way to turn the tables and express yourself in code. - The older a comment is, and the farther away it is from the code it describes, the more likely it is to be just plain wrong. The reason is simple. Programmers can’t realistically maintain them. - Comments Do Not Make Up for Bad Code! One of the more common motivations for writing comments is bad code. We write a module and we know it is confusing and disorganized. We know it’s a mess. So we say to ourselves, “Ooh, I’d better comment that!” No! You’d better clean it! Clear and expressive code with few comments is far superior to cluttered and complex code with lots of comments. Rather than spend your time writing the comments that explain the mess you’ve made, spend it cleaning that mess. ```
// Bad: // Check to see if the employee is eligible for full benefits
if ((employee.flags & HOURLY_FLAG) &&
(employee.age > 65))
// Good:
if (employee.isEligibleForFullBenefits())
``` |
I also find TODO comments quite helpful. It requires far fewer brain cycles to process a TODO comment than to parse the code, figure out what it's doing, and make an assertion that it's incomplete.
Comments can also make code much more approachable to junior programmers, who may not have heard of principles like Tell Don't Ask, or Composition Over Inheritance. When I'm working with a junior dev, I find that comments usually reduce the number of interruptions I receive that are along the lines of, "Hey why did you do this thing this way?"
Really, it's just not a good idea to make sweeping generalizations like, "Comments are always failures". The real world has time and budget constraints, and comments are sometimes the most effective way to satisfy those without screwing the next developer to read the code.