Use Comments Well

I was watching a ball game on TV, and the pitcher was really struggling. He had walked the last two batters, and the manager and catcher went out to the mound to talk with him. It was obvious that the manager wasn't ready to take the pitcher out of the game, but was going to give him some advice. The play by play reporter asked the color commentator what was going on. "You were a catcher; what does the manager say when he gets out there?" The color commentator thought a moment and said, "He says, 'Throw strikes.' And the pitcher says, 'I'm trying to throw strikes.' And the manager says, 'Yeah, but throw strikes.'"

Telling you to comment well is rather like telling the pitcher to throw strikes. It's a great idea, but how exactly do you do it? Well, your comments should never speak for the code. For example:

   myCounter++;  // increment myCounter

This is worse than useless. The code speaks for itself, so get rid of the comment. There is always the danger that the comment will get out of date and you'll end up with:

   myCounter += theNewValue;  // increment myCounter

Now instead of being just obvious, it is plain wrong. Comments should only be used to clarify obscure code. Ideally, of course, you should endeavor to make your code less obscure, not paper it over with a comment. Don't comment:

   a = j / 60; // compute how many minutes

Instead, you should make the code clearer:

   howManyMinutes = howManySeconds / SECS_IN_MINUTE;

Comments should be used to explain what a section of code is for, not what it is doing. Use complete English sentences; the extra effort involved is paid back in extra clarity. By the same logic, try to avoid abbreviations. What seems exceedingly clear to you as you write the comment will seem cryptic some months later. Use blank lines and white space to help the reader understand what is going on. Separate statements into logical groups.

© 1998 by Wrox Press. All rights reserved.