posted under category: Software Quality on March 2, 2019 by Nathan
People don’t like to talk about real standards for commenting your code. They give you abstract thoughts and ideas, then back up and say just do what your team decides to do. Certainly consistency is important, but what if you are consistently bad? This is why I like Code Complete by Steve McConnell. Steve lays down hard figures. You may not agree with him, but he will get you to form an opinion, even if it’s contrary. So in the same spirit, let me talk about what I think you should comment.
First off, I want to remind you that comments are at a different level than the code. As Code Complete says: “Good comments don’t repeat the code or explain it. They clarify its intent. Comments should explain, at a higher level of abstraction than the code, what you’re trying to do.”
Comment every code file
Classes should describe what they are, as simply as possible. View templates should explain their purpose. I think commenting directories with a readme is also nice.
Comment every method
Preferably, comment your methods within a metadata block that can be used to generate documentation for you later, if your platform supports it.
Comment to describe ambiguous variables or acronyms
Typically these may be endline comments on the variable declaration to avoid confusion.
Comment on blocks of code
Again, comments should be on a higher level, and should not detail /how/ a block of code works, but should explain why a block of code is here and what its purpose is.
Point out when you are doing something non-standard, or something particularly clever that may be hard to follow.
What do you think? Not enough or too much? What am I missing?
When Not to Comment Code
Almost as important as when to comment, is the inverse.
- For starters, don’t comment if you don’t have anything to add. Don’t comment just because you don’t see enough comments in the code you are looking at.
- Don’t comment if you don’t understand the context and the intent. Your comment will just be inaccurate.
- Don’t comment to explain every variable. Not unless it’s really necessary.
- Never comment a file change history. That’s what source control software (like Git) is for.
- Don’t comment descriptions on obvious variables.
User_Name; // This is the user name
I, Nathan Strutz, IT and computing professional for over two decades and senior level programmer at the world’s best aerospace company, being of sound mind, fully deputize you with the rights, the permission, and the duty to delete comments that match these parameters. The world will be a better place when these useless code comments are gone.