When and How to Comment Your Code

My previous post on code commenting was intentionally adversarial to make a point:

code comments have been overdone and oversold to developers!

However, here's when you should put comments in your code.

1. Teach

Is there something novel in the way you did what you did? Does it stand out from the solutions elsewhere in the codebase?

If so, teach why.

2. Explain

I'm not the only one who has finished something that can obviously be done better. We can't execute on all 3 sides of the software development triangle.

Tell the next person (including you in the future) you know it can be improved and how. If it isn't obvious to them, then it gives them a way to use the Boy Scout Principle at the very least.

3. Contributions

Leave TODOs when you know there is something to be done next which can be taken on by contributors. If you have an open source library or project, this helps them get going with helping you out.

This is especially great when they are easy wins that don't make a huge impact, which is why you didn't do it in the first place.

Yes, comment your code, but only for a specific purpose - a goal.

Comments powered by Talkyard.