Comments are one of the most useful language features; in practically any programming language. Yet, they can become really a pain. Just consider the following example that I have seen quite often in different variations:
// now, return the difference between the two results return result1 + result2;
// at this point x must not be negative return a - b;
You could surely give me even better examples of counterproductive comments. In fact, this thread contains a long list of funny comments in the code.
Because such things really happen, some people come up with guidelines like, “never use comments in your code — make the code self explanatory.” While the direction looks sound, I would not go so far as to making it an ultimate rule.
I guess, we need to accept the shortcomings of comments; instead, let me show you a technique I was taught by my colleague that helps mitigate one comment-related problem.
We are only addressing one of a number of problems. It can be illustrated with the following example. Suppose I need to call a function written by someone else, and its name (for reasons beyond our control) is far from indicating the purpose. After performing an investigation, we share our findings:
// while the name does not suggest it, // the following initializes the necessary devices: // listener, translator, etc. // this call cannot be moved down c.go(); bool ans = process_test_request(); if (ans) report_success();
Suppose, one year later, while fixing a bug someone decides to remove the call to
go from this code and put it elsewhere, to a more appropriate place. Because people usually ignore comments, only one line gets removed, and the comment now — inadvertently — applies to the next line:
// while the name does not suggest it, // the following initializes the necessary devices: // listener, translator, etc. // this call cannot be moved down bool ans = process_test_request(); if (ans) report_success();
This problem occurs regardless of whether we put comments before or after the corresponding code. It would have been avoided if the comment were put in the very same line as the code: this way you remove comment along with the code. But for long comments, that do not fit into one line, usually this solution is not practical.
In such cases it is worth to consider the following style of commenting:
c.go(); /* while the name does not suggest it, the above initializes the necessary devices: listener, translator, etc. this call cannot be moved down */ bool ans = process_test_request(); if (ans) report_success();
This way, when someone removes the line and forgets to remove the comment, he immediately gets a compiler error.