Simple Programming Advice: Put Examples in Comments

Just a quick note encapsulating some simple advice I'd only discovered recently: Put examples in your comments. Comments should add something to the code. Explaining what the code should do is good, how is bad, since the code itself should say how.

There's a school of thought that says that comments are dangerous, since they easily get out of sync with the code, becoming dangerous lies. So, don't comment, and make your code readable instead. I certainly have some sympathy with this viewpoint, but I think it's naive. For a sufficiently complicated algorithm, each step may be clear and well-named, but the overall structure and intention may still be mysterious. Very little code is designed to be readable by someone without an awful lot of context, and I think this is a real shame.

So, for comments to add value they should do something other than what the code does. A terse and formal description of what the function should do is well and good, but can sometimes leave the reader confused. By illustrating the same thing in another way, through some examples, you've got a much better chance of having the reader understand what you're up to.

The trendy programmer will point out that you can move the formal description of the function out into a set of pre- and post-conditions, and you can convert your examples into test cases. By doing this, you can ensure that your 'comments' never become out of sync with your code. In theory, yes. In practice, the Test Driven Development book made incredibly heavy weather of developing even the simplest of functionality, and I worry about how it scales up.

One day, maybe. In the meantime, comments explaining 'what' plus examples, please.

Posted 2011-08-24.