Agile Zone is brought to you in partnership with:

I've been working on web based projects built mainly with PHP and JavaScript, where I mostly use Zend Framework and jQuery. I am interested in any webpage optimizations techniques - for a faster web! Stoimen is a DZone MVB and is not an employee of DZone and has posted 96 posts at DZone. You can read more from them at their website. View Full User Profile

Four Things to Know when Writing Comments

07.06.2010
| 11780 views |
  • submit to reddit


Every developer has been learned from his teachers how important is to comment his source code. You should comment the classes, the methods, the logic, etc. However nobody explained how exactly to code with comments between the lines. Have you ever seen that

i++; // we increment i with one

That’s a shame! This doesn’t tell you anything, and what will happen if sometime later somebody sits in front of that code? He’d be amazed!

How To

In fact the task is not to determine what are the bad parts of not commenting the code, but how to overcome this. How to write comments. Here are some basic advices.


1. Think about the other developers

First of all the most important thing is to write comments with other programmers in mind. They should understand the logic of your code from your comments and not from the code itself.

2. Write in English

Even you’re not a native English speaker, and you English is not so good, it’s a must to write in English. This is really important when you work for a open source project when always there’s a big community around the project, you cannot be sure that everybody understands your language.

I know that this is difficult – also for me the English is not my native language, but that’s really a must. Once you start doing it, you’ll see that it’s not so difficult.

3. Comment the methods as a black box

Don’t write in a method comment what technique is used to achieve the result. It’s good to describe what the method does, not how it does it.

Bad example:

/**
* returns $a + $b
*/
public function sum($a, $b)
{
return $a + $b;
}

Better:

/**
* Returns the sum of two numbers
*
* @param number $a
* @param number $b
* @returns number $a + $b
*/
public function sum($a, $b)
{
return $a + $b;
}

4. Comment the logic, not the technical solution

When there’s a loop or a statement it’s useless to describe that this is a loop or statement, isn’t it? A better approach is to describe in a comment why you needed to implement this logic in such way.

Wrong:

...
$arr = array();
$i = 0;

// in a while loop we
// initialize every element with 0
while ($i < 100) {
$arr[$i++] = 0;
}
...

Better:

...
$arr = array();
$i = 0;

// we initialize an array of 0s
// to store the sorted elements
// on the first pass... etc, etc.
while ($i < 100) {
$arr[$i++] = 0;
}
...

Conclusion

In fact the most important thing is to write comments with other developers in mind. Tell the future developer of that code what’s in the code, and pray for mercy ;)

References
Published at DZone with permission of Stoimen Popov, author and DZone MVB. (source)

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

Comments

Ricky Clarkson replied on Tue, 2010/07/06 - 7:08am

Instead, strive to write code that does not need comments.

Ronald Miura replied on Tue, 2010/07/06 - 7:15am

5. Think a little harder about whether you should write a comment, or make the code more understandable.

I'm not as radical against comments as some people but, most times (inline) comments do exist just because the code is crappy. Try to make your code cleaner before you write a comment.

Anyway, if you feel more confortable writing comments than refactoring code, maybe you should consider switching careers to documentation authoring ;)

PS.: javadoc comments for public methods are mostly welcome, unless they are stupid too obvious:

/**
 * Returns the name
 */
public String getName() {
    return name;
}
hint: IDE-generated comments are always bad, turn them off.

Bino B. Manjasseril replied on Tue, 2010/07/06 - 9:07am

I recently read this quote somewhere: "Real Programmers don't comment their code. If it was hard to write, it should be hard to read" - Unknown.

Josh Marotti replied on Tue, 2010/07/06 - 12:12pm

I've always been taught to comment functions/methods, but nothing more granular.  If something INSIDE a method needs commenting, you are probably better off extracting it to its own method and commenting the new method.

Jonathan Fisher replied on Tue, 2010/07/06 - 3:31pm

I agree with the first response. Code comments are 'excuses'. If you do it right the first time, your code reviewer doesn't need comments to figure out what's going on.

Jeroen Wenting replied on Wed, 2010/07/07 - 3:49am

"Even you’re not a native English speaker, and you English is not so good, it’s a must to write in English. "
Wrong. We're a company working purely on the local market, for local customers employing local people. Those customers demand we use our native language (which isn't English) for all communications, including documentation and comments.
I will prefer to use English for entity names because mixing native language with English in phrases (and code lines are phrases) just is weird, but javadocs are going to be native language by corporate policy unless the customer demands otherwise.

"Comment the logic, not the technical solution"
Sometimes the technical solution demands documentation in comments. And no, there isn't always a simpler solution available.

Philippe Lhoste replied on Wed, 2010/07/07 - 6:35am

I would be curious to see the code of those against the usage of comments in code!

Sometime, a line of comment explains what kind of little known API is used and what for: it avoid a lookup and an interupt in the reading. Sometime, we have to explain why we chose a given algorithm instead of another: it can avoid that another programmer breaks the code by replacing it with the rejected one. Sometime we have to explain why we do some things, because the frameworks acts in surprising ways... And so on.

For example:

   if (visible)
   {
      // Must check if the mouse is still over the window, because mouseExited
      // is called when cursor goes over the combo boxes.
      Point pt = new Point(e.getPoint());
      SwingUtilities.convertPointToScreen(pt, (Component) e.getSource());
      if (!IsMouseOnWindow(pt))
      {
       // No longer over the window, just hide it
         SetInvisible();
      }
      else
      {
         // Start a timer: if after some time, the mouse is still exited and no longer over the
         // window, the cursor probably went directly (quickly) from a combo box to outside
         // of the window, thus not triggering a mouseEntered/mouseMoved/mouseExited sequence.
         m_checker.start();
      }
   }
 

 I hate bad comments as well as other people, for example:

   // Visibility defaults to false
window.setVisible(true);

and I appreciate long variables/functions/classes names, but telling that code is always self-sufficient, even with doc comments (like JavaDoc) is a bit extremist.

Mikael Couzic replied on Wed, 2010/07/07 - 6:55am

This book answered to all the questions I had on the subject :
Clean Code - Robert C. Martin

An absolute must read !

Geza Radics replied on Wed, 2010/07/07 - 10:38pm

The other thing is that many times one doesnt want to read every line of your code, in most of the case he just want to find the place where he should fix sth. 
Maybe it doesnt fit to every situation but if a function is longer then it should be I always use this kind of commenting:

//=== FIND THE BOOK FIRST =========
[...]
//--- first check it on the table --------------
[...]
//--- second check it on the self ------------
[...]
//=== CHECK THE CONTENT ==========
[...]
if it is a small issue //check both front and back 

so that the programmer can skip many lines to read, but still knows what is happening there. 
This might be not the best example, because in this case the first block could go into a 
separate function, but it is not always the case. I use this because if you alway use the same 
style of commenting everywhere it is hard to distinguish which one is important and which one if 
negligible. It is also fit to point 4. Writing the comment first also helps to plan the function.

Stoimen Popov replied on Thu, 2010/07/08 - 6:19am in response to: Ronald Miura

Hi, nobody says you should stop writing code and start writing comments. However when you write code it's obviously the most important thing to do, but does that mean that you should stop writing comments, just because the code is "super understandable"?

Gar Labs replied on Tue, 2011/08/23 - 10:37am in response to: Bino B. Manjasseril

This quote is good. That's the best quote I've ever read for Learning and Programming. -GAR Labs

Emma Watson replied on Fri, 2012/03/30 - 6:01am

I discovered that if the code is well-written, properly divided up into classes, functions and modules and has intelligent function names then heavy commenting is counter-productive.

Swing

Comment viewing options

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