Best practices for writing code comments

Best practices for writing code comments

Unravel the art of writing code comments that enhance readability and maintainability. Discover how to strike the perfect balance between too much and too little, and learn to craft comments that illuminate rather than obscure your code's intent.

Rules to achieve a happy medium

Comments should not duplicate the code

Explain unidiomatic code in comments

Without the comment, someone might “simplify” the code or view it as a mysterious but essential incantation. Save future readers time and anxiety by writing down why the code is needed.

Links to standards and other documentation can help readers understand the problem your code is solving.

Use comments to mark incomplete implementations

Sometimes it’s necessary to check in code even though it has known limitations

If you can’t write a clear comment, there may be a problem with the code

Debugging is twice as hard as writing the code in the first place

Conclusion

Comments don’t excuse or fix bad code, they complement good code by providing a different type of information

Comments should dispel confusion, not cause it

If your comment causes confusion instead of dispelling it, remove it.

Including a reference to the source enables future readers to get the full context, such as: what problem was being solved, who provided the code, why the solution is recommended, what commenters thought of it, and how it can be improved.

Comments should not duplicate the code

Comments that add no information have negative value because they: add visual clutter

Good comments do not excuse unclear code

Don’t provide information that should have been in the code.

Add comments when fixing bugs

Comments should be added not just when initially writing code but also when modifying it, especially fixing bugs.

Source

Get in