Re: Top Ten Errors Java Programmers Make
On 12/9/2009 7:59 AM, Patricia Shanahan wrote:
RedGrittyBrick wrote:
[...]
Nowadays I try to avoid making comments that make work for myself.
It's a good thing to remove comments that merely restate what the code
says. These are the sorts of comments that are most likely to need
maintenance when code changes.
I agree with this except for two types of comments:
1. Interface descriptions, such as Javadoc comments. Someone who just
wants to know the preconditions and postconditions for a method should
not have to read its code, let alone the rest of the code in its class.
2. Descriptions of variables. Even if the meaning of a variable can be
deduced from the code, it is often much easier to read the code
knowing what its variables mean.
May I add a third type? The "why" comment for a section
of code can be important, the comment that explains (or cites)
the reason for doing something (or for not doing it).
/* Rebalance the Frammis to minimize the flimflam margin
* (algorithm P from TAOCP section 3.1.4.1.6)
*/
/* No need to synchronize here: We already hold the
* Lochinvar lock
*/
/* Make the defensive copy *after* instantiating the
* MuggleModel
*/
.... and so on. There's a fairly extreme example in a piece of
my own code, where a two-line method
private static int peakUsers(int users, double frac) {
double stdev = Math.sqrt(users * frac * (1 - frac));
return (int)Math.round(users * frac + 2 * stdev);
}
.... also carries a thirty-two-line comment giving the reasoning
behind the two lines. The "what" is clear from the code; the
"why" requires explanation.
--
Eric Sosman
esosman@ieee-dot-org.invalid