While there are many resources to help programmers write better code—such as books and static analyzers—there are few for writing better comments. While it's easy to measure the quantity of comments in a program, it's hard to measure the quality, and the two are not necessarily correlated. A bad comment is worse than no comment at all. Here are some rules to help you achieve a happy medium.
- Comment the Why, not the What:?I strive to write code that is self-explanatory in terms of what it does. My comments are then dedicated to providing context, explaining my decisions, or highlighting any non-obvious aspect of the code.
- Keep Comments Relevant:?One of the things I've learned the hard way is that outdated or incorrect comments can be worse than no comments. So, every time I update my code, I make it a point to update relevant comments as well.
- Avoid Redundant Comments:?As tempting as it might be to comment everything, I avoid commenting on the obvious. I believe that if my code is clean and clear, it should largely speak for itself.
- Use XML Documentation Comments:?I find XML documentation comments an excellent tool to provide information about my code's classes, methods, properties, etc. Not only do they help generate a separate XML file, but they also provide IntelliSense documentation in the Visual Studio code editor, making life easier for me and my team.
- Commented-Out Code:?Early on, I used to leave commented-out code in my source files, but soon I realized that it creates unnecessary clutter. I've come to rely on source control for remembering old code instead.
In the end, I would say that code commenting is truly an art form. When done right, it can greatly enhance the understandability of your codebase and improve productivity for both yourself and others. And always remember, your comments are a reflection of your thought process, so strive to make them as clear as possible.