Naveen's Weblog

Bridge to future

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

  1. Classes
    • What does the class do?
    • Which other classes are used by it?
  2. Methods
    • 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)
  3. Comment Complex lines
    • 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.
  4. Give appropriate names to variables and Methods
    • 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.
  5. Read the comment twice after writing
    • 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

Other references:

Happy learning,
Codingsense 🙂


One Response to “Why and how use comments effectively”

  1. […] Why Avoid Exception Why and how use comments effectively […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: