Tuesday, September 05, 2006

rsonal preference art : The Art of Commenting

Mike Clark wrote an interesting piece on comments, and I have a few things to contribute as well.

Here are some of the practices I follow with regards to comments:

I configured Eclipse so that whenever I create a new class, it inserts a JavaDoc comment that says "This class ". Yup, that's right. Just these two words.

I found that modifying templates so they contain fragments of sentences forces a reaction in me. As soon as I see them, either I go ahead and edit them to complete the sentence, or I delete them completely. Which is much better than seeing five lines of text saying "This comment was generated in a template. To configure your template, go to Windows / Preferences /...".

I like to add comments for closing braces:

I don't know about you, but to me, a closing brace means nothing. I have no idea what it applies to and while I can obviously put my cursor on it and find its matching pair (Ctrl-Shift-p in Eclipse), it's actually much better to write it down explicitly. This kind of comment helps me understand the algorithm I am looking at much better and sometimes, even spot bugs right away ("Shouldn't we close the file outside the for loop?").


There is a big difference between a JavaDoc comment and a regular comment. This is a point that seems to be absent from Mike's article but it's a very important one. For that reason, I find it acceptable to be less strict when you are writing a non-JavaDoc comment (you don't really need to supply an @param for each parameter of your method). I also tend to reserve the /* syntax for JavaDoc comments and multiple // comments for the rest (this is purely a matter of taste).

I like to comment blocks of code at a time, as opposed to commenting lines. For example, I will spend two-three lines describing a for loop at the top of the said loop but I will probably not bother adding extra comments inside (there are exceptions to this rule if the loop is particularly complicated, of course).
These are all more or less personal preferences, but there is one rule that think should be applied at all times:

http://beust.com/weblog/archives/000286.html

0 Comments:

Post a Comment

<< Home