Three Ways Not to Use Comments in Code

By

programmerCommenting code is by some considered a code smell or anti-pattern in itself: code should be self explanatory. I agree that a lot of comments could have been left out in the first place. I think comments serve a purpose though, used in the right way. However, here are three ways not to use comments in code.

Commenting Out Code

Commenting out code while developing and debugging is ok, but don’t leave it hanging around. This has grown to epidemic proportions as most IDEs now offer a shortcut to do this. Simply press CTRL+/ or some other easy to access shortcut and you just commented out a hundred lines of code.

Commented-out code is confusing. No one dares to remove it, either. It must have been left here for a reason, right? For example:

List gizmo = getGizmo();
// for(int i = 0; i < gizmo.size(); ++i) {

// checkValue(gizmo[i]);

// }
build(gizmo);

Instead of commenting out code, learn how to use your version control system. It is easy to go back to earlier revisions and review code that has been deleted. If you get into the habit of writing meaningful messages when committing, chances are you will even understand why the code was removed.

Stating the Obvious

Don’t use comments to state the obvious. For example:

/**
* Hoozit getter.
*
* @return The hoozit
*/
Hoozit getHoozit() {
return hoozit;
}

If you feel you need to write a comment about what the code does, chances are you should refactor it instead. In a perfect world, comments explain why while the source says what.

Making Code “Readable”

Don’t add markers, dividers, and so on, to make a source file readable.

In modern editors you have enough tools at your aid to navigate between methods and classes: there’s no need to clutter files with separators like:

// ========= Private methods ==================

Commenting end of blocks is usually not a good idea either. It makes maintaining the code more difficult, and is probably a sign you should refactor the code. It can also be a sign that you should rewrite the code. For example, having several levels of nested loops makes the code hard to read and leads some people to add a comment by the closing bracket. It is often a better idea to break out the loops into own functions, or rewrite the code someway else.

Conclusion

Be sure to comment your code. However, take care to do it in a meaningful way. It is likely that you, or someone else, is going to read the code in a distant future. The comments are as important as the code it annotates.

No comments:

Post a Comment