About a year ago I wrote an article on comments. That article left me feeling uncomfortable. In it I made a point that people may think that their code is too simple to need comments. Indeed, it is not beyond the realms of possibility that this is in fact the case.
I’ve been reading a book called “Clean Code – A Handbook of Agile Software Craftsmanship” by Robert C “Uncle Bob” Martin. He devotes a whole chapter to comments – which is highly commendable. His thoughts on comments can roughly be surmised by the following extract:
The proper use of comments is to compensate for our failure to express our-self in code. … We must have them because we cannot always figure out how to express ourselves without them. … Every time you express yourself in code, you should pat yourself on the back. Every time you write a comment, you should grimace and feel the failure of your ability of expression.
Despite my earlier post, I have reached the conclusion that I agree with him! Indeed, the argument “My code is too simple to need comments” should describe the code you are aiming to write. Being objective in your analysis of your code is the hard part. Martin’s main objection to comments is what I was alluding to in my earlier post: they tend to “rot” by becoming less reflective of reality over time if not maintained along with the rest of the code base.
A lot of the early chapters of Clean Code revolve around the “common-sense” aspects of coding.
Variables should be descriptively named (as should functions and classes)
Functions should do one thing and one thing only.
Functions should be short. (In fact, as Uncle Bob puts it: “Make a function short, then make it shorter”)
The second strategy I recommended for writing comments was to “pretend you were explaining the block of [complex] code to someone else”. As Martin states, this is a failing of the code. You would be better off refactoring the code so that it wasn’t so complex. If you apply the “common-sense” aspects of coding, you will probably find that your complex code violates at least one of the rules.
I was pleased to see that Martin suggested that comments were okay when written to convey the intent of the author. This is still my number one use for comments.
It’s been an interesting read so far and I am sure there will be other topics that I wish to reflect on in blog form. Expect to see more in the coming weeks!