Commenting code is a part of development and engineering that is overlooked all too often. It might be that developers are simply under so much pressure that they feel there is no time for commenting. It might be viewed as a hassle. And, it is not something that is required for the code to compile and execute.
The compiler sees comments as optional, but that does not mean that developers should see them the same way.
Commenting is a vital, I would even go as far as to say critical, part of any software engineering effort. If you have been in the business for any length of time, you have undoubtedly come across code that is missing meaningful comments. You probably spent a significant amount of time trying to figure out not only what the code was doing, but what the original author was intending to do. Perhaps you have even experienced this with your own code!
Try to get in the habit of adding meaningful comments while you are coding, and do not consider the project finished until the comments are in place. Often, the comments in code are the most up-to-date documentation that a project will have. Requirements and technical specs may be out of date once the coding actually starts, and keeping documentation up to date which is separate from the code is a much more complex task than keeping comments up to date. If you use Java, take a look at the article How to Write Doc Comments for the Javadoc Tool. Look at the Java source and see how the comments are formatted. With a little practice, commenting will become second nature.
What if you do not use Java? That’s ok — every language has some way to leave comments, and the principles apply just the same.
Here are five ways to make commenting work for you:
1) Comment the method signature before you write any code inside the method. Then write the code implementing the described behavior.
2) Comment private methods and fields, not just public ones. You can then tell the javadoc tool to include private classes in the generated documentation. The resulting javadocs will be invaluable for anybody that needs to maintain the program in the future. You can easily generate two sets of documents if needed, one for public use and one for private, internal use.
3) Update comments when you modify the code. Comments that do not match what the code is doing are not helpful.
4) Take advantage of version control keyword expansion in your comments. For example, including the CVS keyword $Id$ in your comment will tell you who checked in the file last, the date, the RCS filename, and the revision number.
5) Let your IDE do the work. Modern IDE’s understand javadoc comment format, and can often generate the boilerplate of the comment for you, including @param, @return, and @throws tags. You just have to fill in the blanks.
What other ways do you make comments in code work for you? Feel free to leave a comment below, and tell us about it!