No matter which language I’ve written code in, the one common feature has always been “the comment”. Usually comments are described in the language definition along the lines of “ignored by the compiler”. Given some of the code I’ve seen, I could almost extend that definition as “ignored by everyone”. It shouldn’t be this way people!
Like most of the problems / issues I see in the computing industry, the problem here is one relating to poor communication. Better communication invariably leads to better collaboration. Code comments are under-rated. Whenever I have read texts referring to when and where to use comments, they have seemed to come up short. Most texts will tell you to avoid making obvious statements and instead use them to explain complex logic. The problem is, when you are coding “in the zone” even the most complex multi-threaded, recursive algorithm seems straight-forward.
The first mistake when writing comments is therefore defined as “My code is too simple to need comments”. AKA “Anyone can read the code and determine what it is doing”. In this regard, you’re probably right! Most decent programmers could look at your code and determine what it is doing. But is that what you intended it to do?
The second mistake with comments is using them to comment out code. This practice is okay when you are debugging code, but no completed work needs a “dead code museum”. Revision Control Systems are perfectly adequate for keeping a log of how the code used to look. You do use a Revision Control System, don’t you?
The final mistake made with comments is ignoring them. Over time, code changes and as such sometimes comments written will no longer accurately portray the code it is written about. If you see an inaccurate comment, FIX IT!
As to how to write effective comments, here are two strategies to try.
- When writing a new function, start by writing the comment. In this comment, list the steps you will use to solve the problem. Then write the code, breaking the single comment up into multiple ones, interspersed with the code needed to perform the action as defined by your comment. When you’re finished, you should have a good suite of comments guiding the next developer through the thought process you used to solve the problem.
- When altering existing code, put in a “placeholder” comment whenever you look at a block of code and wonder what it is doing. Once you’ve got the placeholders, go back and pretend you are explaining the block of code to someone else. Listen carefully to yourself, because there’s your comment. Remember, that bug finding is so much easier when a decent comment describes the “intent” of the code, rather than what the code is doing.
Whilst there may be other good strategies to use when writing comments, starting with these two should see you off in the right direction. If you’ve got any other pet advice on what makes a good comment, feel free to leave me a comment on this post!