Sunday, November 8, 2009

How to Properly Comment Code? (Part II)

It took longer than expected to find the time to write the second part, but finally here it's

For some reason, the last month has been full of articles about commenting code, like Is Commenting Your Code Useless?, Code Comments: The Lowest Form of Communication or Comments are a sign of bad code

You're free to visit those sites and see their arguments. I must say that I only agree with the first of them, in fact this article is almost a duplicate of his arguments.

When should I comment my code?

To properly answer this question you need to look at your code and think if your comment is improving in some way the understanding of what you're doing.

// We're done
isDone = true;

Is not really helpful, is it? Your comments must aggregate some value to your code, otherwise are worthless.
Also you must always keep in mind that your code should be clean enough that's self-descriptive. Keeping your code self-descriptive have 2 benefits. The first one is that you'll not need to add comments, the second, and most important, that will make things easier when arrives the time to maintain it  (and believe me, this time will come).

Only in the case that your code is not descriptive enough, you must add a comment. Is that bad? not at all.

My code is self-descriptive, why should I comment it?

Some pieces of code can be quite complex, mainly when you work in real projects. You only need to thing about financial, graphic or simulation software. They require tons of complex coding to achieve their objectives and it's usually quite hard to get the mentioned self-descriptive code.

Even when your code can be really clear, the purpose of this code may be not. I'm going to copy a good example from Jani

//Calculate if two circles intersect
$xd = $c2->x - $c1->x;
$yd = $c2->y - $c1->y;
$diameter = $c1->radius + $c2->radius;
$intersection = ($xd*$xd + $yd*$yd) < ($diameter * $diameter);


Simply reading this code would be a bit hard to known what's happening. The variable names could help, but the comment is giving us the final information

1 comment:

  1. The last code snippet is a great candidate for method extraction... so a descriptive name for a method eliminates the need for such comments.
    Thanks.

    ReplyDelete