Friday, September 6, 2024

10 Best Practices to Follow While Writing Code Comments

Comments are an important part of writing code not only in Java but whatever programming or scripting language you use. At the same time, this is one of the most abused things as well. Both writing no comment and writing too much comment is bad and this has been highlighted by many software gurus e.g. Robert C. Martin in his classic book Clean code. There is a whole chapter dedicated to How to write comments and finding the pros and cons of a comment. This article is my learning in the same direction, here I am going to share with you guys some 0f the rule and best practices I follow while writing comments.

Before that let's first see what is the purpose of having a comment in the code? Why do we need comments, isn't writing code is enough. Some of the people I have met always argue that we are getting paid for writing code and not comment :).


Anyway, in my opinion, we all agree with each other that software spends only 10% time of its life in development and rest of 90% in maintenance. This 90% part of maintaining the code is where comments can help you immensely. 

Since no single developer stays till the whole life of any product or software and its often new people, who work of already written code. 

These are the people who read the code and not aware of why a certain piece of code has been written, here comments can help them to understand code quickly and believe me you will get lot of roses from that fellow developer :). 

Anyway long story short here are some of the things I try to follow while writing code:



10 Tips on writing code comments



1) Readability

Focus on the readability of code; assume that you don't have comments to explain the code. Give your method, variables, and class meaningful name.


2) Don't write what code is doing

There is no point to write what the code is doing, this should be left for the code to explain and can be easily done by giving class, variable, and method meaningful names. For example:

//calculates square root of given number 
//using Newton-Raphson method
public void abc(int a){
       r = a / 2;
       while ( abs( r - (a/r) ) > t ) {
       r = 0.5 * ( r + (a/r) );
       }
       System.out.println( "r = " + r );
}
 
The above code is calculating square root using the Newton-Raphson method and instead of writing a comment you can just rename your method and variable as follows:

public void squareRoot(int num){
       root = num/ 2;
       while ( abs(root - (num/ root) ) > t ) {
       r = 0.5 * (root + (num/ root));
       }
       System.out.println( " root = " + root );
}
 

3) Explain Logic or Reason 

Always write why you are writing this piece of code, why you are writing this piece of code because this information is not visible until you write them in comments and this is critical to identify any bug or behavior with changing the business environment.


4) Follow Established Standards

If you are writing core libraries which will be used by different project and with different teams. Follow Javadoc commenting style and document all assumptions and precondition for using your API. 

Joshua Bloch has also mentioned about writing Java-doc comment in his classic Effective Java, which is worth knowing.


5) Include JIRA Number 

It makes sense to include JIRA Number and description on comment, especially if you are modifying an existing piece of code as part of maintenance. This I found extremely useful while comparing different version of code in CVS or SVN. 

This gives you clear idea why that particular code has been added and whether issue is because of that piece of code or not.


6) Keep it Short

Always try to finish your comment in as few words as possible, one-liner comment is best until it's explaining the "Why" part and can't be replaced by code itself. Nobody likes or has enough time to read longer comments.


7) Don't put already available information

Don't write a story in the comment as your name, employee id, your department, etc because that information can be obtained from Git commit data in case someone wants to know who has made this change.


8) Don't commit the Code without comment

Always put comments while committing code in the source control repository and especially why you are adding this piece of code if possible include JIRA or QC Number so that anyone can refer JIRA for complete details.




9) Create a Comment Guideline for Team

If you want upcoming developers to follow certain standards or inform about certain things then include them in the beginning of your class as a comment

For example, suppose if you are writing a serializable class in Java then it's good to put a serializable alert stating that any new fields added in this class must implement a Serializable interface in java or make it transient etc.





10) Avoid Duplicate Comment

Just like duplicate code, duplicate comment is also bad.

There is no point putting duplicate comments on each and every git commit. Since your code is changing, try to put what the commit is doing instead of copying the blanket and duplicate comments from the previous commit. 




Code comment Cheat sheet

And, here is a nice summary and code comment cheat sheet which you can print and stick to your desk and follow while writing code comments:

Code comment Cheat sheet



That’s all from me on code commenting, please share the standard, best practices, or your experience with writing comments on code. I believe these are the areas in which a junior developer or even we can improve and it’s only possible from learning which each mother's experience.

Last but not least give your code to the fellow developers to understand as part of code review and ask him how much he understands it.


Happy weekend :)


19 comments:

  1. I'd like to add that for javadoc comments it's best to use plugin in IDE like Checkstyle. This plugin will make sure you won't forget writing javadoc comments.

    And also it's crutial to write comments while you are writing a code. Not days/week/months/years later. You should never say that you will write comment later, because you won't. And if you do anyway, such comment will likely suck.

    ReplyDelete
  2. @Kumar, Thanks for your comment man. good to know that you like this post.

    ReplyDelete
  3. cool tips buddy, specially javadoc comments and having JIRA number in comments , I personally follow it

    ReplyDelete
  4. "5) Include JIRA Number and description on comment,"

    Better to create a unit test with descriptive name instead putting jira related garbage into your code.

    Personally as TDD practicioner I'm preferring "test-as-documentation" principle to explain my intentions, bugfixes or other changes in the code.

    Another great place to put non code relevant comments (jira numbers, etc...) is the version controller's submit comments.

    Try to keep as low as possible the comments in your code and use unit tests to explain...

    ReplyDelete
  5. Hi!

    I suggest that you read Clean Code (http://goo.gl/5EyY) chapter about code comments.

    Bye, Karlo.

    ReplyDelete
  6. Hi,
    I totally agree with most of your advices,
    but prefer not to writing javadoc in most cases.

    See http://asolntsev.blogspot.com/2010/05/why-devil-invented-javadoc.html for more details.

    PS. In 2. example, I would still add comment "// using Newton-Raphson method" because it's not clear from code.

    ReplyDelete
  7. Here's my rules, and I have my asbestos underwear on so flame away:

    1) Don't write comments. Write better code.
    2) Comments are an excuse, and you should only excuse something if you can't do it better.
    3) Rather than write comments, use a design pattern. Convention (design patterns) are far superior to excuses.
    4) If the business logic is so complex that it makes a small piece of code unreadable, it's a good time to add a comment.

    ReplyDelete
  8. writing a software required lot efforts and hard work.Your tips about writing software helpful too much.Planing is must for writing a software.

    ReplyDelete
  9. @Lexandro, writing unit test for maintenance code is not a bad idea, it certainly valuable but some time one line comment can do magic and allows to understand some important points about code which is require to think through various scenario.

    ReplyDelete
  10. @asolntsev , Thanks for link buddy, though java doc is more verbose it suits great for API but yes there are better alternatives on code commenting .

    ReplyDelete
  11. @thecodemechanic , you must be awesome very competent developer man , someone borne with great coding and programming skill with natural ability of think through to write software which works on every possible scenario, but not all people are gifted buddy. though I personally appreciate your advice but that is just an ideal situation.

    ReplyDelete
  12. I suggest, reading comment section of Clean code book from Uncle Bob, lot's of good advice there e.g.
    1) Code is your best form of comment, make code speak for itself.

    2) Only write comment which gives information, which is not visible from code e.g. don't write, what code does, what type it is, instead write name of algorithm if code id more cryptic.

    3) Don't litter code with TODO comments.

    ReplyDelete
  13. That's the ideal case mate. If you can avoid, than yes, best avoid writing comments, but sometime you need it; and then these best practices can help you to write better comments e.g. WHY part is very important, a simple statement describing a complex algorithm is worth writing.

    ReplyDelete
  14. Checkstyle project is considering to add support for Comments validation , please support proposals at https://groups.google.com/forum/#!topic/checkstyle/VEVFDsZKLzg

    ReplyDelete
  15. What code doeas and how it does are two different things.
    The //using Newton-Raphson method comment should have remained.

    ReplyDelete
  16. Thanks for writing this post.

    ReplyDelete