Good source commenting is a kind of art

It’s my firm conviction that good inline source commenting is a kind of art. It’s not easy to find the right balance between too much and too little commenting in your code. And it’s even harder to write useful comments.

I recently came across the following code snippet:

// Number of pages
doc.setNoOfPages(t.getPageCount());
// State
doc.setState(t.getState());
// Text
doc.setText(t.getText().trim());
// Code
doc.setCode(t.getCode());
// GroupCode
doc.setGroupCode(t.getGroupCode());

This is a good example of completely useless comments. Even worse, the comments bloat the code!

I personally think most comments should be avoided in favor of good method names. In my experience, inline comments are often hints for possible code refactorings.

Another example from the same code:

// Rotate (Convert marker into boolean)
char rotate= t.getRotationMarker().charAt(0);
if (rotate == '1') {
    doc.setRotate(Boolean.TRUE);
} else {
    doc.setRotate(Boolean.FALSE);
}

Here we have, in fact, two separate operations and the comment states exactly that: “Rotate” means “setting the rotate property” (and is another example of a useless comment) and “Convert marker into Boolean”.

What about creating a small conversion method?

/**
* Converts a charcter value into a boolean.
*
* @param rotate Character to convert. A value of "1" will be
* interpreted as TRUE and all other values as FALSE.
*/
private Boolean toBoolean(char rotate) {
    return Boolean.valueOf(rotate == '1');
}

The calling code is then as follows:

boolean rotate = toBoolean(t.getRotationMarker().charAt(0));
doc.setRotate(rotate);

Now you have a simple JavaDoc comment and a separate setter with no comment.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s