Comments are important but don’t forget that your code should also be self-commenting.
If I had to sum this episode into a single sentence, I’d have to say that comments should explain why some code is not obvious. And this is after you’ve done everything you can to make the code obvious in the first place.
If you find yourself writing a method called getName and then adding a comment that says, “This method returns the name,” then your really might want to reconsider the need for that comment. And going the other way, if you find yourself writing a method called performWork and then adding a comment that says, “This method calculates the average value of the input stream of numbers,” then you might want to just rename the method to calculateAverageValue instead.
In both of these examples, instead of either making the comment redundant or relying on the comment to explain what the method really does, it’s much better to just let the code document itself. Choose descriptive names for your methods, class names, and variable names.
When you’re designing software, one guideline that will help you keep your design understandable is to limit the scope of what a class or method does.
If you’re having trouble coming up with a method name and the best you can think of is performWork, then maybe that’s because the method is trying to do too much. It’s a clue that if you’re thinking about something as just a mass of work, then it could probably be divided into smaller and more descriptive methods. And if you do try to use descriptive names and find yourself with a method called readDataAndCalculateAverageCheckWinningMove, then it should be obvious that method is trying to do too much.
Listen to the full episode for more including a couple common mistakes that developers sometimes make with comments.