3 ms·
Funny that #10, 'Comments that explain the “how” but not the “why”', quotes from an article by Jeff Atwood to show how the comment should have been written. But
by edanm 16y ago
Funny that #10, 'Comments that explain the “how” but not the “why”', quotes from an article by Jeff Atwood to show how the comment should have been written. But in the original article, Jeff actually says that that commenting style is also not as good as refactoring the code:
"That must be what I was getting at, right? Some sort of pleasant, middle-of-the-road compromise between the two polar extremes of no comments whatsoever and carefully formatted epic poems every second line of code?
Not exactly. Rather than add a comment, I'd refactor to this:
private double SquareRootApproximation(n) {
r = n / 2;
while ( abs( r - (n/r) ) > t ) {
r = 0.5 * ( r + (n/r) );
}
return r;
}
System.out.println( "r = " + SquareRootApproximation(r) ); "
- dagw 16y agoI'd consider that new code a step backwards since it removes the vital words "Newton-Raphson". If I didn't recognize the algorithm I might have a very hard time working out exactly how and why that lump of code approximates a square root. With the words Newton-Raphson included somewhere I could easily look it up and find out everything I need to know about not only how and why it works but also its strength and weaknesses. Personally whenever I use some non-trivial algorithm I haven't made up I tend to include a comment pointing to the book or paper I got it from so that others can get the canonical description of what the algorithm does. Ideally I'd even like to see a brief comment on why Newton-Raphson was chosen as well. Is there a good reason why I shouldn't replace that code with some other square root approximation technique or was it chosen because it was the only algorithm the author knew?
- edanm 16y agoI agree that the algorithm name should appear somewhere. I would probably refactor the code as Jeff says, but add a comment that describes the function, probably with details about why it's implemented the way it is.