Why comments are badYou may now think of me as of an idealist. Thinking of a world without conflicts, religion, etc. Well, it’s nothing like that. Every source code requires more or less comments, but in most cases, when you may want to write one, most probably there’s a better solution.
Why do I state that using comments is bad?
Comments can get quickly outdatedConsider this piece of code:
Comments need to be read along with the codeIsn’t this a purpose of comments existence? Well it actually it is, but if there’s a comment then it means that reader needs more time to get through the code because he or she needs to analyze code and all the comments. It’s not only the matter of how much there’s to read – code that needs a comment can be understood only when reader can get understanding of a comment – so there’s as twice as much things to analyze.
Now I’d like to show you some real scenarios in which comments were used, as well as how it can be improved and why.
Use meaningful variable namesSomething so obvious, yet frequently ignored. How often did you stumble upon variable names like a, b, x2, etc.? Let’s take this code example:
One more note about variable names: for loops are frequently using a counter variable. It’s perfectly legal to use “i” or “j” as a counter name since it is widely used style of naming. The same applies for “x”, “y” and “z” while we’re making operations on coordinates.
Do not use magic numbers“Magic” numbers are numerical values that exists inside methods and it may be difficult to know why these numbers are set in a particular way. Magic numbers should be extracted into variables, fields or even class constants with meaningful names.
Do not explain ifsIf you have an if statement and it may be not clear what it does and why, you may be temped to make a comment to that statement. Before you do, think of extracting your if () condition (what’s inside) into a meaningfully-named method.
- By extracting if condition we could move distance calculations into a separate method so Update() function has much less code to read now.
- EnemyIsNearPlayer() function name is self-descriptive. We do not need a comment here.
Watch out for function parametersSee this code?
SummaryAt first glance it may look like producing more code instead of using comments for much simpler code, but trust me – this will greatly make you and your colleagues’ life much better in the long run.
Still, if you feel that a comment is really needed and there’s nothing else to do – go ahead! There are situations where you cannot do much about it. Yet remember that the information in your comments may someday become outdated, so keep it simple and safe.