The one certain time you should add comments to code is when the code can’t or doesn’t explain itself.
I read a lot of code. And thus, I read a lot of comments. Many are useless and distract from reading the code. Take this, for example:
int countOfSortIterations = 0; // Count of Sort Iterations, defaults to zero.
But sometimes, comments are literally… gold:
This comment is key to succeeding in using this code, or maintaining it, or in using this code as an example/pattern for some other way you are going to use this API.
I asked the engineer about it, since he’s a very tight coder that generally doesn’t add many comments:
In this case, the comment is essential. The comment is the only documentation available. It wouldn’t be as critical if the library had some other kind of documentation. It’s still useful to document in the code because you’re more likely to update the comment when the code changes.
If this comment wasn’t here, somebody maintaining or using this code is going to waste hours (days??) sorting out what needs to happen or why things aren’t working.
This suggests a good guideline for deciding when to add well-written explanatory comments:
What can I say that is critical for maintaining or using this code that the CODE CAN’T readily explain on its own?
Comments, like all other parts of code, should be lean and have a specific and necessary purpose.