Why and how use comments effectively
Posted by codingsense on May 22, 2010
A code is said to be good by the quality of comments it contains. A code with good quality of comments will save a lot of time and help to understand the code quick and better and while maintaining software and avoid regression bugs. Many products and companies do not strictly follow writing of comments in the product. So if your product has no comments or little then start writing the proper comments.
We should have Comments for
- What does the class do?
- Which other classes are used by it?
- What does the method do?
- What are the inputs and return type?
- What changes to the system is done by that method (if it is updating a database or xml file or a static variable of some other class etc)
- Emphasis more on why the below line is required than what the below line does (e.g. assume the scenario in which we are iterating a list and we are incrementing the List index by one, instead of writing the obvious “Increment the index by one” write “move to the next element in the list by incrementing the index by one”)
- Write comments to only the lines which are not obvious. Comments will be required majorly for algorithms or if it’s changing the behavior of a system.
- Giving proper names to variables and methods for what it does help to understand the obvious lines much better, avoid comments for such lines. Like if I have a variable named hasOperationFailed, by just looking it I can be sure that it’s a Boolean fields and while checking the conditions like If(hasOperationFailed) makes me understand what condition am I checking.
- This may seem to waste time but trust me, after reading the written comment again we tend to re write the lines many times. Since the value of comments can only be said by the reader who uses it. So if the lines are simple to understand and appropriate then your efforts will be considered.
There are software’s that fetches the comments from your code and gives the output in different formats so that you can verify your comments and it can be used as a guide for what your classes and methods does.
Here are the list of some