I’m a big advocate of comments. It conveys the programmer’s intent, which is very useful if you’re interpreting someone else’s code.
Comments should explain intent
Code shows what the program does.
Comments should explain the intent behind the code.
For example, this comment is useful:
// Calculate the student's final grade from exam and homework scores.
double calculateFinalGrade(double examScore, double homeworkScore){
return examScore * 0.7 + homeworkScore * 0.3;
}
The comment gives the reader a high-level understanding of the function before they read the implementation.
This is especially useful when the code is part of a larger system. A reader may not care about every implementation detail immediately.
Another example. This comment explains a design trade-off.
// A vector is used here because iteration is frequent and insertions are rare.
std::vector<Item> inventory {};
It tells the reader that the container choice was deliberate. If a future programmer considers replacing the std::vector with a linked list, the comment gives them context before they make the change.
Avoid comments that merely repeat the code
Some comments add no information:
// Set sight range to 0
sightRange = 0;
The code already says that. The comment only repeats the statement in English.
This kind of comment creates clutter. It doesn’t provide any new information.
Explain why something is done
Good comments often explain reasoning.
For example:
// Clamp damage to zero so high defence does not heal the target.
damage = std::max(0, attack - defence);
The comment explains the rule, not the syntax. The reader can see that std::max is being used.
Commenting out code
In addition to providing documentation, comments can be used for the following:
- Assist in debugging. If a program fails to compile, you can comment out code sequentially to identify the culprit.
- Permit compilation. If a block of new code is causing a compilation error, you can comment it out and return to it later.
- Refactoring code. Rather than delete the old code, program the new code and test it, you can comment out the old code as a backup. Then, when the new code passes the tests, you can remove the old code.