Code Comments: novice programmers either use too much or too little, while so called “experienced programmers” don’t even know where they should be placed.

Actually, the proper use of code comments is one of the issues in software engineering with the least amount of debate. Overall, there are only two rules of thumb to keep in mind when using code comments.

Comments should explain the why instead of the how or what.

In other words, your comments should not repeat what the code is saying. Code Complete uses these two examples:

//set product to base
product = base;

//loop from 2 to "num"
for ( int i = 2; i <= num; i++ ) {
    //multiply "base" by "product"
    product = product * base;
}
System.out.println( "Product = " + product );
//compute the square root of Num using the Newton-Raphson approximation
r = num / 2;
while ( abs( r - (num/r) ) > TOLERANCE ) {
    r = 0.5 * ( r + (num/r) );
}

System.out.println( "r = " + r );

Both code snippets don’t look good (i.e. the variable names are bad). However, only the latter’s comments are useful, and the former would be better off with no comments at all.

If the code is so complicated that it needs to be explained, it’s nearly always better to improve the code than it is to add comments.

There are many ways to do this, ranging from using more descriptive variable names to inserting white space when needed. My personal favorite is to extract methods.

...

//get user input
...

//process user input
...

//format and display output
...

In this case, the programmer crammed all of the logic into one function. This usually happens when the developer reached his state of “flow” and just keeps on typing hundreds of lines of code into the system. The problem with functions longer than a couple of dozen lines is that not only is it hard to read, it’s also hard to debug.

By extracting the logic of the comments, we can have clearer code without even using comments, not to mention an easier to debug program:

public void run() {

	getUserInput();

	processUserInput();

	displayOutput();

}

private void getUserInput() {

	...

}

private void processUserInput() {

	...

}

private void displayOutput() {

	...

}

And yes, this is post is a lame excuse for trying out the SyntaxHighlighter plugin. :P

Tagged with →  
Share →

Leave a Reply

Google+