Posted: June 19, 2022
Good code comments are good. They help the reader better understand what’s going on with the code.
Bad code comments are bad. Bad comments are worse than no comments.
Bad code comments generally fall into two types.
One type of bad code comment is a wrong comment. This kind of comment makes a statement that is factually incorrect. Like this:
# Calculate the circumference result = pi * radius^2
(πr² is the area of a circle, not its circumference.)
Sometimes wrong comments are just due to a programmer misunderstanding or mistake. Frequently, they can result from changes to existing code that render the comment incorrect. (So, kids, when fixing or changing existing code, be sure to update the comments too.)
Another type of bad code comment is the unhelpful comment. Like a bad play-by-plan announcer, this comment uselessly explains what you already plainly see.
# Calculate the result result = pi * radius^2
These kinds of comments often are authored by inexperienced coders. They’ve heard that code comments are important (true!) so (by gum!) they’re going to write a comment.
Comments should be used for explaining things that are not clear from a simple reading of the code. If you can make the code clearer, maybe you don’t even need a comment. In the examples above, I’d consider changing the “result” variable to “area”, giving:
area = pi * radius^2
There, no code comment needed – unless it would be helpful to explain why the area is being calculated. Otherwise, comment not required.
Sometimes no comment is the best comment.