Code comments are a funny thing. Most of the mistakes I see with code comments stems from the author writing the comment from their perspective. That comes easy to most of us. We already know the full context about the code, and we just want to write something in plain english to help explain what is going on.
The problem with that is that we are not the ones who are going to be the audience of the comment. The audience is going to be our fellow developers for the next 1000 years that will see this code and wonder “what in the world is happening here??!!”
Here are some tips on writing good code comments!
Avoid writing a comment that explains what the code is doing. The code should be clear enough that other people can figure out what the code is doing. If they aren’t able to do that, then refactor the code to make it more clean and understandable.
// BAD
// Get a random number between two values.
var x = random(a, b);
// GOOD
// Use a random number so that no two requests are ever alike because
// those would be flagged as duplicates and need to be fixed by users
// which is a waste of their time.
var x = random(a, b);
If you find yourself wanting to write a comment to explain what the code is doing, then it’s better to work on making the code cleaner. Perhaps things need better names, or the logic can be simplified.
Clean code is better than clever code.
// BAD
// Return whether or not it's archived unless it's an expense report
return $isArchived ? ($isExpenseReport ? 'report' : 'not a report') : 'not archived';
// GOOD
if ($isArchived) {
return $isExpenseReport ? 'report' : 'not a report';
}
return 'not archived';
Don’t forget, as the author, you have ALL THE CONTEXT! No one else has that context. Keep the assumptions and context needed to understand a comment to a minimum.
// BAD
// This is a hack to speed up performance.
// GOOD
// Use a lookup table to improve the performance of calling
// this function when looping over large datasets.
So many comments I read are addressed to different groups of people (eg. “We need a file to exist”). Who is “we”? Why do they need it? Does someone else not need it?
Typically, comments like these come from a good place. They are usually intended to reference all the developers that will ever be working on this system. However, that’s entirely unnecessary in a code comment and not information that is useful in the majority of comments. It’s like giving a variable the name originalData . It’s a given that a variable holds data, so don’t include “data” in the name.
// BAD
// We need it to exist
// GOOD
// A file must exist
// BAD
// If you need to skip this, its OK
// GOOD
// Skip creating the file because the file already exists