Sandeep is a ITA at Tata Consultancy Services. He also is the author of java blog. Sandeep has posted 24 posts at DZone. You can read more from them at their website. View Full User Profile

Best Practices for Commenting Code

04.09.2012
| 5165 views |
  • submit to reddit
Adding comments to code is an important part of writing Java programs. Though it is recommended to add as many comments as possible in your code but still there are some best practices which if followed really make code commenting a useful affair not only for the developer himself but also fellow developers.

Here in this tutorial, I will list down some tips and guidelines for writing the code comments in a Java program:

  1. Add comments for each ending block so that it is clear which code block is going to end.
        While(...){
    
    if (abc==xyz)
    {
    for(...) {
    } //for
    } //if
    } //while
  2. Format the comments so that they are properly aligned and break to next line if exceed the viewable area. This helps in getting rid of extra scrolling just to view the comments.
  3. Use proper language and avoid frustating comments like:
        //Finally got it
    
       //hahahaha
     
       //you can't escape from me
    
  4. Comment out the code which could be reused in future but could not be implemented this time.
  5. Focus on why part of the code and explain the need of code you are going to write.
  6. Usually the bug id is also added when you are working on some enhancement/bug so that other developers can get the need for the code.

Published at DZone with permission of its author, Sandeep Bhandari. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Nicolas Frankel replied on Tue, 2012/04/10 - 1:16am

I was expecting much from your title, sadly, your content only gives weight to people telling the code should be self-sufficient.

  1. Any good IDE worth is salt renders this point moot. Really, are we back to vi?
  2. See point 1
  3. OK
  4. No please! Don't do that... ever! Just use a SCM and be done with this practice from before
  5. Cannot understand the sentence
  6. Requirement ID would be OK. Once the bug is closed, however, I could care less there was one in the first place, so this only clutters the code and make it less readable

 

Tomasz Nurkiewicz replied on Tue, 2012/04/10 - 2:17am

Unfortunately I can not agree with most of your suggestions:

1. Or maybe - use proper indentation and extract nested blocks into separate methods rather than nesting while/if/for?

2. Any IDE can do this, also screens today are much wider. If you are writing comment longer than 100-140 characters - you might have bigger problems.

3. Agree. We are no longer in kindergarten.

4. No! Use version control system, this is what it is for.

5. If you meant: explain why the code was written and not what is it doing, than agree.

6. I tend to add bug ids to commit messages rather than cluttering the code, but this is subjective.

Konrad Malawski replied on Tue, 2012/04/10 - 4:50am

I'd like to just comment these rules with: "No. Just... No."

Tomasz already wroteup point-by-point exacly my thoughts about them, so I won't be repeating myself here - just a big "+1" from me there.

A major pain point is leaving "commented code for future use"... I guarantee you it's going to be forgoten and useless the next time you see it anyway. And if code is not tested and/or running in prod it's just plain useless - learn to live with it - delete that code ;-)

Tech Fun replied on Tue, 2012/04/10 - 7:25am

Funny enough the title is called best practices instead of worst practices. From where I stand, only point 5 make some sense, all the others should be avoided.

 1. if the code is short enough, the braces matching should not be a problem even in notepad. So keep methods/classes short!

 4. never do this. 

 5. the only thing code could not explain is the why. So explain why instead of what - "what" is explained by code itself

6. try to avoid this, instead, put bug id in checkin msg. 

Bob Damato replied on Tue, 2012/04/10 - 7:42am

Yup... I agree with the others. Read Bob Martin's Clean Code Handbook. He asserts that comments can actually be detrimental to your code. As your code changes, your comments quickly become misleading or flat-out wrong (who really goes through the trouble to read the comments and fix them when code changes?). It's better to simply write clean, expressive, readable code with understandable class, method and variable names and you'll be just fine. That's not saying comments are unnecessary... classes should be given a brief description on why they exist and public methods can generally benefit from a sentence or two, but commenting loops, non-functional code, bug ids, and "why" you wrote something just make clutter and confusion.

Benrhard Fischer replied on Tue, 2012/04/10 - 7:52am

Just one observation for point 1 I made at the company I'm working for: 

there is one guy who is often commenting ending of blocks (he's only responsible for very specific parts of our source-base) - but that guy is visually impaired - he's blind - so I guess for him these seem to be very helpful comments

however - I would never comment like this - every IDE - even vi(m) - can show me matching braces - or even highlight whole blocks of code
and for the other points I have to agree with the other comments before

Jammer Man replied on Tue, 2012/04/10 - 8:38am

Wow, this needs a title change: 6 commenting mistakes you must never make.  Apparently this person has never heard of an IDE or source control.

Mark Unknown replied on Tue, 2012/04/10 - 8:45am

I really hope this is just his thoughts and not representative of a larger group. When i came across comments like this in code I know I am in for some trouble - both in the code and the comments. I delete all comments like 1,4,6.

Jonathan Fisher replied on Tue, 2012/04/10 - 10:05am

Don't comment your code. Comments are an excuse for poor engineering or writing horrible code.

 

Instead:

 

  • Add debug statements.
  • Write better code that is clear in it's intent
  • Use lots of small functions named intuitively (the JIT compiler will go to town on this)

 

Paul Holser replied on Tue, 2012/04/10 - 11:41am

Comments are apologies.

Chuck Dillon replied on Tue, 2012/04/10 - 1:44pm

WRT "comments are apologies"

For the most part I agree with the sentiment and in an ideal world comments would never be needed.  But in this real world there are caveats.  There are cases where there are limitations in the technologies that force one to do non-obvious and/or unavoidably ugly things.  There can be pitfalls in an underlying design that aren't going to be refactored out in "this release".  In these cases you need to give those that follow (possibly you) some insight into the caveats and pitfalls that lurk.

Example, during late stage testing you discover a bug in a 3rd party API which aint gonna be fixed in time for your release but you have a workaround which requires some non-obvious code to be added.  Sure you could write a method and name it WorkaroundForFooLibBugThatPreventsDeterministicFreeingOfResources_DoNotRemove() but you are commenting either way.

Also when you are implementing complex analytical code (e.g. implementing a high order math or signal processing algo) you should add comments that describe what you are doing in the language of the technical domain you are using.  For example the mathematical formula/method you think you are implementing and/or a reference that is unambiguous.  In these cases variable names typically follow the notation of the method (e.g. sigma, psi...) and you need a reference or comment to define these.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.