Code Comments Should Explain ‘Why’ Instead Of ‘What’

I’m a comment minimalist. I don’t believe in commenting what code does. That should be plainly obvious by reading the code itself. More useful is why a block of code exists or why it was written a particular way. These are the questions I ask most often when reading code (including my own) so I try to be conscious of it when writing code.

If I’m writing something I think might be challenged other developers I’ll write a comment to defend my position and explain the circumstances and tradeoffs which had to be made for that piece of code to exist the way it does.

If I’m writing something based on assumptions which I’m fairly certain will change over time I’ll write a comment to explain the assumptions and speculate on how they may change over time. I’ll try to provide ideas on how to deal with those changes when they inevitability happen.

If I’m cutting corners because I’m working under unreasonable time pressures and need to ship something in the extremely near future I’ll write a comment to explain why I’m cutting a particular corner in a particular way.

If I’m writing a complex piece of logic I’ll try to summarize what’s happening in addition to why it has to be complex. Further down the road other developers may try to simplify this complex logic so it helps to anticipate how someone might attempt this and explain why it won’t work.

If I’m writing something in a non-obvious way for performance reasons I’ll write a comment to explain why along with some sample benchmark comparisons if appropriate. Someone in the future may try to rewrite it in the obvious way but will be unaware of the performance tradeoffs involved. It’s good to explain these things to ward off future regressions.

Of course, this ignores the whole world of documentation comments. These are the style of comments which conform to a standard format which can be parsed to produce nice looking API documentation for references purposes. This is a great thing and I fully support it. It’s practically required for certain types of projects with developer APIs. However, in my experience working on ‘custom/closed’ projects I’ve found it extremely difficult to get everyone to actually write these kind of comments consistently. For documentation comments to really work they have to be applied completely and consistently. My overall philosophy is this. If you are willing and able to write good documentation comments then please do. If not, then fine. But you must at least write comments explaining the why of a chunk of code in any of the above cases.