No, your code is not so great that it doesn’t need comments
Code-commenting is so basic and so universal that every programmer, regardless of the language that they practise, thinks that they know all there is to know and that their way is the only sensible approach (I am no different in this respect). I guess that’s why there are so many blog postings offering advice on commenting (you can add this one to the list).
Even the elite of programmer bloggers are having their say. Steve Yegge covered it and, more recently, so did Jeff Attwood. Jeff’s basic advice, that you wouldn’t need so many comments if you wrote the code to be more self-explanatory, is sound but the idea that we should be aiming for some kind of perfect code that has no need for any comments is dangerous.
It’s not a sensible goal for beginners and inexperienced developers. Tell them that they should write good code without any comments and they will deliver on the second part but struggle with the first. Even among experienced developers, assuming for a moment that it is possible to write perfect code that doesn’t require comments, there will be far fewer who are capable of this than there are who think that they are.
The other arguments against commenting are even weaker in my opinion. Yes, poor comments are …well… poor. So don’t write poor comments, write good ones. And yes, if comments become out-of-sync with the code then they are not helpful. So don’t let the comments become out-of-sync, they are part of your code and should be maintained/refactored along with the code itself.
I don’t believe that I’ve read a piece of code and thought “wow, this has far too many comments”. Unfortunately, I’ve had the opposite reaction all too often. I don’t for one moment believe that it is possible to write quality code without any comments. Take Jeff’s own example:
Here’s some code with no comments whatsoever:
r = n / 2; while ( abs( r - (n/r) ) > t ) { r = 0.5 * ( r + (n/r) ); } System.out.println( "r = " + r );Any idea what that bit of code does? It’s perfectly readable, but what the heck does it do?
Let’s add a comment.
// square root of n with Newton-Raphson approximation r = n / 2; while ( abs( r - (n/r) ) > t ) { r = 0.5 * ( r + (n/r) ); } System.out.println( "r = " + r );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) );I haven’t added a single comment, and yet this mysterious bit of code is now perfectly understandable.
Sorry Jeff, but that’s not “perfectly understandable”. I agree with extracting the square root code into a separate method with an appropriate name, but your second version (the one with the comment) was more informative since it mentioned which algorithm you were using (in your version, the maintainer is going to have to figure that out for themselves). Also, we’re still left with at least two poorly-named variables. We can forgive the use of n for the parameter since that’s kind of a convention but what the hell are r and t?
In my opinion, this is better:
/** * Approximate the square root of n, to within the specified tolerance, * using the Newton-Raphson method. */ private double approximateSquareRoot(double n, double tolerance) { double root = n / 2; while (abs(root - (n / root)) > tolerance) { root = 0.5 * (root + (n / root)); } return root; }
Alternatively, if you don’t like the verbose comment at the top, you could either rename the method to something like newtonRaphsonSquareRoot (if you are happy for the method name to be tied to the implementation) or put an inline comment in the body explaining that this is the Newton-Raphson method. Any of the three variations will communicate useful extra information to the maintenance programmer, who can then Google “Newton-Raphson” if they want to find out more about it. Remember that code is written only once but read many times. It should be tailored for the reader rather than the writer.
This is all very well, but we’re still lacking some information. Why the hell is Jeff calculating square roots in this way? Why is he not using the library function? Is it because he doesn’t like the answers it gives him? Is it for performance? Who knows?
Well-written code will often answer the “what?” and “how?” questions with few or no comments, but you often also need to answer the “why?” question too. Avi Pilosof covers this in his response to Jeff’s post. Avi argues that rather than comment the code, you should comment the business justification for writing the code that way. This may mean inserting reference to particular requirements or issue reports.
So yes, favour code that is self-explanatory, but I don’t believe that you can always achieve the necessary clarity without a few well-placed comments to aid understanding. Code that is obvious to the author today is rarely obvious to the maintainer next year (or even to the author next month).
And if you still really believe that your code does not need any comments, then I hope I never have to maintain your code.
on July 26th, 2008 at 12:17 am
Im sorry mate but I’m with Jeff on this. And I posted why on his comments. Basically, if I’m a math dude and I see this: SquareRootApproximation(n), and scan the following code I can almost instantly figure out what it is and what it does. With a comment I would have gotten the same exact information. Not lets say I’m one of those programmers that are not current with their maths. And I see either, I’m still not going to have a clue about what’s happening and I’ll end up googling either the comment or the procedure. And I’ll end up in wikipedia reading about Newtons method. Jeff’s code is as readable as needed and had no need for comments. You may not feel the same now but when those huge LCD’s you bought to have various code windows at max height actually don’t make the experience any better because you’re looking at a gazillion comments instead of well formatted code, you’ll agree that in programming less is ALWAYS more.
on July 26th, 2008 at 1:07 am
James, as you can probably guess, I disagree wholeheartedly.
I don’t get what you say about Googling for Newton’s method. What are you going to use as a search string when Jeff’s not giving you any hints?
My monitor has plenty of room for a couple of lines of comments. In my experience, code is rarely as “obvious” as the author thought it was. Also most IDEs and editors will display comments in a different colour, usually a paler colour that is easily ignored if you want to focus on just the code.
And if I do find some code that is over-commented, it is easier to remove the comments than it would be to reconstruct comments that were missing but necessary.
on July 26th, 2008 at 1:16 am
Also, because Jeff’s code doesn’t answer the “why?” question, should I, as the maintenance programmer, replace it with a call to Math.sqrt? Seems like it would be a nice simplification, but maybe Jeff is keeping something to himself about why he did it this way?
on July 26th, 2008 at 6:09 am
Dan, I expected that much
it would be no fun if you agreed with me.
What I mean is that the moment I read this: SquareRootApproximation(n) and see the code in question I either immediately know what the procedure does and how it does it, OR I just don’t get the what or the how. Now IF I don’t get it right there what will I search for? This: “square root approximation”. The result? I’ll end up in wikipedia learning what, why and how of Newtons Method (and probably a whole other bunch of stuff). This is probably the same I’ll find if you put a comment like the one you posted.
I’m not saying that comments are bad. My whole point is that 1) better written code without comments is better than crappier code with more comments 2) since my day job basically has me coding all day long, and I need to work with other people’s code, I’ve been in a situation where I’m looking at code in a maximized terminal (i use a 30inch LCD and a macbookpro at work) in a remote server and all I see is an ocean of comments, and few lines of code. In this case comments not only where a nuisance, but an obstacle 3) sometimes comments ARE necessary, like you say. But to be honest… most of the comments I see everyday in my job and in my freelancing projects, are just excuses to NOT write self explanatory code.
On the “why”:
/**
* Approximate the square root of n, to within the specified tolerance,
* using the Newton-Raphson method.
*/
This doesn’t explain why either! If your really have to explain why, you would probably use a whole screen with a comment rivaling a wikipedia article on newtons method. In my opinion the only comments that MUST explain the why are generally a block at the begging of the program, or object, or w/e, giving a broad overview.
In my case… I use comments only to summarize a very general description of what the program does and how it does it at the beginning of the source. And the only why I explain is business logic. And business logic has more to do with client requirements and obstacles, than with any logic having to with programming itself.
PD: sorry for the long post. I get carried away sometimes
on July 26th, 2008 at 6:11 am
By the way I like your site. You seem to have some good content here. I’m gonna add you to my newsfeeds
And If I end up doing an article on commenting when I finish my site redesign Ill probably end up pointing everyone here. Good job on the site once again.
on July 26th, 2008 at 11:55 am
I must dissent as well. I practically never comment the code. JavaDoc is a whole different animal, sorry. You’re not commenting the code but providing help to other users that are not reading the code but using an IDE to invoke it or browsing some public doc repository.
on July 26th, 2008 at 3:07 pm
James, I think we have a basic agreement that self-explanatory code is good and that *some* comments are necessary, we’re just disagreeing on the extent of commenting that is (or should be) necessary. Also, I disagree that lots of comments is particularly harmful. Even something ridiculous like Jeff’s example of the procedure header at the beginning of his post wouldn’t really bother me. Code that needs comments and doesn’t have them is far worse.
You’re right about my comment still not explaining why, but then I don’t know why the code is written like that
If it had been me writing that routine, I would have written just a single sentence to explain why I felt it was sensible to calculate square roots in that way.
on July 26th, 2008 at 3:09 pm
Jose, whether it is Javadoc or not is not really important in this particular example, escpecially since it is a private method. What I am arguing is important is that the information should be communicated in some way. I think we’re all in agreement that some of that information can be communicated by sensible naming of methods and variables. I’m arguing that additional information is necessary and that means adding comments (Javadoc comments, single-line comments, whatever).
on July 26th, 2008 at 5:24 pm
Can’t agree more. Tell me why you did that! That’s what I run into all the time. I can usually tell what the code does, I can’t tell why it does it. Most library I find on the net suffer this. This and how to use. This square root example is probably a too simple example for people to see the value of saying why and “how to use”.
I think you point out what others seem to miss. If the comments are badly written and what was written is useless, don’t blame the fact of commenting. Blame the programmers who don’t learn how to properly communicate to other programs! That’s the right target.
“Let us change our traditional attitude to the construction of programs. Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do.” – Donald Knuth
…
“Programming is best regarded as the process of creating works of literature, which are meant to be read.” – Donald Knuth
I spend hours fixing code written by others who were poor in commenting. Yes, if you do a comment lines count you’ll get some — mainly commented out code or idiotic comments like:
// add a and b together to get c
c = a + b
Well of course that’s an idiotic comment and not worth being there. Ok, so what should I tell the programmers when I train them — don’t write comment because that poor guy wrote that? No, I should use that as an example to say: see, tell me how that helps you. It doesn’t, ok, so this is what you should not do! And then have them drilled on expressing themselves to others, remedy their communication problems if they have one because I know that their communication problems is what is going to give me the biggest problem down the road when I have to fix someone’s code that does not tell me why and I stare at my screen trying to figure out what to change because I can’t tell if there was a management / executive decision to do it this way instead (e.g. why is a added to b, maybe I should add a1 too to it… seems like it should).
So, as I said, you nicely pointed out the correct target and I’m glad to see others thinking like that. I can’t way until I can take somebody else code and not work for hours just to understand it.
on July 27th, 2008 at 9:26 am
[...] came across Dan’s blog entry later the same day and realized that he too makes a good point. Both sound absolutely [...]
on July 27th, 2008 at 4:33 pm
It’s my philosophy that if you find yourself writing a comment that describes what a method does, either the method does too much, or you should use that comment AS the name of the method. Try something like this:
newtonRaphsonSqRootApprox( double number, double tolerance )
And if you need to conform to a standard interface, then delegate! Delegation is your best friend.
approxSquareRoot( double number )
{
return newtonRaphsonSqRootApprox( number, 0.0001 )
}
on July 27th, 2008 at 4:36 pm
Also… if you don’t want to add a private delegated method, then consider abstracting that behavior into an Operation class that performs the square root operation. (Java for example, here)
This strategy even lets you change behavior of your square root operations at runtime, at configuration time, and it lets you extend the behavior to use other algorithms without changing your client code.
public Class NewtonRaphson implements SquareRoot
{
public long squareRoot( double num );
}
on July 27th, 2008 at 4:43 pm
I agree that comments are really important, not only for your self, but for other developers. My code looks like a novel when I’m done with it, I load it up with comments.
on July 27th, 2008 at 8:08 pm
I totally agree with you but I also really don’t understand this whole discussion (I am coming from Jeff Atwoods article and already read some others take on it).
Even if this square root approximation was a good and general example (which it is not, because it is far to simple), it still lacks some valuable information, which is not totally evident by just briefly reading the code:
– Passing in negative values result in an endless loop. Of course you can’ compute the sq.root of a negative number, but it would be good if I knew how the function handles this (which actually might be going into an endless loop, as long as it is documented).
– Passing in zero results in a division by zero. This is a bit obscure, because it actually would be computable. Still it might be a valid limitation (say, performance reasons), but I need to know that!
– What happens with differenct values for tolerance (say, 0 or even a negative value). Currently it might result a endless loop, but again…
It really doesn’t matter how much you try to avoid to document your code. There is always so much a maintainer or user of a function might need to know, which can’t be easily extracted by the best written code.
Don’t fight it, just get better at documenting what you do. Be as concise as you can in your comments and your code.
on July 28th, 2008 at 12:34 am
Most of the time the why is incorporated into the context of the program.
“Im creating a utility for a math teacher to check and make sure that the students answered his random questions correctly”. All of a sudden all of the various approximation methods do not need a why.
I have never seen a block of code, written by me, or by the coders that came before me that needed a why.
public String AesEncryption(AesKey key, String foo){}
does that really need a why? _if_ a why is needed it is needed where it is called, not at the method. Then again the context of the calling method will probably tell you why.
on July 28th, 2008 at 12:51 am
I’m a poor commenter, but the truth is I’m a poor programmer too. That’s why I don’t comment. I’m never sure if I’m doing things the right way, so I wait until I’m absolutely positive that what I’m doing is going to work. By that point my mind has moved on to the next problem. I know this is bad practice but I have trouble correcting it.
on July 28th, 2008 at 1:08 am
I don’t know how many times I’ve come back to a piece of code that I’ve written after six months or so, and then spend ten minutes to figure out where I need to do a thirty-second fix. I agree with Dan that there’s no such thing as over-commenting (unless you just get ridiculous about it).
Additionally, you should attempt to descriptively name all functions, subroutines, and input/output variables so that they can be identified on the fly.
on July 28th, 2008 at 1:52 am
Dan,
I’m right with you on this one. No one that defends no comments can ever honestly answer that all of their code is self explanatory. We all do funky things with our code sometimes for different reasons. Maybe we choose to use one algorithm over another for some concern that is not obvious looking at the code.
For example, I had the case recently where I added an additional table join to a query because a column was indexed in one table, but not another. Someone looking at the code may just think it’s silly and remove the extra table from the query which would result in a huge slowdown.
No one’s code is “perfect” enough to warrant leaving out comments. Even in a perfect world where you have control of every aspect of your project (such as what columns in your table are indexed), there are many different ways to do almost anything and not every programmer thinks the same way.
on July 28th, 2008 at 2:03 am
Having started my career maintaining c code with a 15- 20 year history of different coders working on it gave me a great appreciation for well written comments. I can only assume that people who don’t comment must have been privileged to only work on their own code never done any maintenance work.
on July 28th, 2008 at 2:29 am
I agree with you 100%. No such thing as too many comments.
What seems obvious to you today might not be in 6 months, or might not be obvious to someone else that doesn’t think in quite the same way as you do.
Or 20 years from now if someone not 100% familiar with the language is asked to port your code to another language, after you are long gone, it will be necessary for them to have those comments in order to do their job.
And when it comes to open source code, there are a lot of beginners trying to learn a little something from your code and the comments would be most helpful, so in the case of OSS development, COMMENT EVERYTHING!
And if you have tried things that don’t work, it might be beneficial to state what doesn’t work in a comment, and why.
// please refrain from putting your grocery shopping list in your comments
on July 28th, 2008 at 2:46 am
[...] Here is the link No your code is not so great that is doesnt need comments [...]
on July 28th, 2008 at 3:27 am
Great post!
I couldn’t agree more. You can try very hard to make sure that every method and class is clear and easy to understand, but at some point it will fail.
I work on a fairly large project, mostly on the GUI side, and constantly run into segments of the code that take me a very long time to traverse and figure out because a previous developer did not bother to comment a method. This is not because the method has a bad signature or because it was poorly written, rather in the grand scheme of the program it doesn’t necessarily follow why it’s there or how it works the way it does.
Good comments allow one to quickly find their way and understand particular quirks or reasons behind the original intent. It’s this “original intent” that can get so easily lost a lead the difficulty for the maintainer.
on July 28th, 2008 at 5:30 am
Personally, I think the “why it is done this way” comments are for more important than the “what it does” comments.
More often than not I can figure out what the code is doing but I cannot seem to fathom why they would do things in such a manner.
on July 28th, 2008 at 8:07 am
[...] Link « Wiki [...]
on July 28th, 2008 at 9:25 am
[...] Postauksessa kerrotaan että mikään koodi ei ole niin hyvää tai itsestäänselvää ettei se tarvitsisi minkäänlaista kommentointia. Kirjoittajan kanssa yhdyn kyllä samaan asiaan, että vastaan ei ole tullut koodia jossa olisi liikaa kommentointia. [...]
on July 28th, 2008 at 9:57 am
The “Newton-Raphson” bit in the comment is helpful. I get a feeling Jeff would agree, as his main point was that you should first try to create readable and self-explanatory code and only *then* add comments where necessary, which is what you did.
on July 28th, 2008 at 10:02 am
> I agree with Dan that there’s no such thing as
> over-commenting (unless you just get ridiculous about it).
Different styles may be preferable by different programmers… I guess we call that taste! For instance, when I download a piece of code the first thing I do is often to remove almost all comments (except function header comments if they look helpful). Not only will that give me a good impression of how long the code is, doing so gives me a good approximation of what the code actually does as opposed to what it says it does, because the latter may be a lie, or well-intended but erronous (i.e. outdated). IMO, saying “never comment” is just as potentially dangerous as saying “there’s no such thing as over-commenting”. The best solution as ever so often is a balance, and I think Jeff’s main point was that self-explanatory code is the first step, and then comments come in to the mix too.
on July 28th, 2008 at 10:09 am
I totally agree with what you are saying. Everyone says that code should be self explanatory, but why is it never just that?
My experience is that when people say that their code doesn’t need comments, they need a code review.
on July 28th, 2008 at 10:13 am
Have any of you read Code Complete? I know that the Microsoft Press label is going to put a lot of you into some kind of defensive stance, but put that aside for a moment please, and give the book a chance. The purpose of comments is to help the people who work on your project when you are gone. Will you manage to finally take a vacation? Go off to play WoW? Either way, if its a good project, it’s going to be around for a while. Someone other than you is going to need to make changes. At least let us know what you are trying to accomplish in your classes.
on July 28th, 2008 at 10:33 am
my thoughts exactly
on July 28th, 2008 at 10:51 am
[...] 28, 2008 at 9:51 am (Uncategorized) Nice article on commenting your code. Please comment your code, if for no other reason than I can at least see what you were trying to do when I come in to fix [...]
on July 28th, 2008 at 11:00 am
[...] Jul. 28th 11:59 h remember: commenting code is good visit weblink 0 [...]
on July 28th, 2008 at 11:21 am
If you haven’t read with too many comments, you haven’t seen the boilerplate that some Java IDE’s churn out for every method, where the comments can be longer than the code themselves.
Too many comments makes code unreadable. Too many comments also means you’ve failed to properly convey the meaning of the code in the code itself.
on July 28th, 2008 at 11:40 am
One of the best uses of comments is to document the contract of the code. In the example you gave, I would have liked to see in the comments a description of what happens if it is called with Double.NaN, Double.Inf, or 0 in either place of the arguments.
Even descriptively written code needs comments, because there are more paths that are rarely executed than paths that are regularly executed. If someone finds a bug, they need to know why you wrote it the way you did. Code, no matter how descriptive doesn’t tell you the why.
on July 28th, 2008 at 12:07 pm
hey dear dan….you are so genius…good comments yaaar….
i prefer your opionon..
on July 28th, 2008 at 12:07 pm
Matthew, you would probably benefit from spending some time each time you have something you are sure works, going back over the code and trying to explain why it works. It won’t just help future maintainers, but it’ll make you a better programmer.
Trying to spot weird and unexpected cases, and documenting what the code does in those cases even if you legitimately decide not to handle it is also a really good exercise.
You could also try some TDD, which it sounds like you’re already doing informally. Formalising and recording the tests you are doing to be sure it works encourages you to think about other cases you might not have considered, and enables you to rerun the same tests if you ever change the code in the future.
on July 28th, 2008 at 12:44 pm
Let’s pretend that you don’t write all code for your own sake. Let’s pretend that there are others that read, consume and debug your code..
on July 28th, 2008 at 1:07 pm
Must agree whit Dan on this one, I think especially “why” is important in the business logic, where code not necessarily needs to be very logical. But it don’t need to be a long comment, just a URI to bugzilla or similar
on July 28th, 2008 at 1:11 pm
I agree with Jeff , whilst your idea of commenting is indeed verbose I don’t really see the need for it , other than to just increase your line count.
on July 28th, 2008 at 2:11 pm
Very interesting points. I am going to think a lot more about my commenting. Thanks!
on July 28th, 2008 at 2:46 pm
Yes comments help in methods, where complicated logic is executed, but if its a simple method, the method name itself should imply the same.
//This is lame
/*
Gets User Info.
*/
User getUserInfo(){
}
on July 28th, 2008 at 3:27 pm
Surely it depends on the context. I work in an agile environment and we comment nothing. However we don’t have to provide an API to anyone, every code check-in is peer reviewed and everything is tested and comitted together. This might not be the same in most open source environments.
If there is ever a doubt as to why some piece of code is in, a quick look at the tests that changed will explain why.
Perhaps surprisingly everyone here can maintain everyone else’s code and personally I say it’s a breeze reading through some code without having to read some comment which may or may not be out of date, comparing it to what the code really does, etc etc. The code is its own comment. Sometimes you get ridiculous function names, like some commenters in this post have always demonstrated, but it’s a small sacrifice for a simple, straight-through readable code experience.
The only doubt might be the ‘why’ question which can sometimes be a problem. I generally solve this in the function name or by a carefully designed test.
on July 28th, 2008 at 3:48 pm
“I have never seen a block of code, written by me, or by the coders that came before me that needed a why.”
All I can say is that you have been very, very lucky. I spend a lot of my time maintaining code that is 10 years old or more. I often come across code that takes seconds to understand, but what you don’t know is why it does it that way instead of the way you would do it. Is there a good reason? have new libraries/techniques appeared in the intervening years? or did they just not know what you know?
You’ll never know the answer to that without rewriting the code the way you think it should be written and then finding out if it works or not.
on July 28th, 2008 at 4:02 pm
I love all the people who think they are such excellent programmers that they don’t need to comment their code. They provide full employment for all the real programmers out there. They also lower the bar for the rest of us, so our performance reviews are glowing even when we are not doing our best.
on July 28th, 2008 at 4:32 pm
I definitely agree with Dan.
This example was meant to illustrate a point, and actually I think it is a good example.
There are not many people, even among programmers, who understand square root algorithms. If I am getting errors when certain values are passed in, I want to know:
1) What the routine is supposed to be doing
2) Why it didn’t do what it was supposed to do.
If you didn’t give any hints as to what square route algorithm is being used, I’m sure as hell not going to go off on some long research project to try to match algorithms to the one in the code I’m trying to debug. What if it’s not even there at all, but some pathetic and horribly broken homebrew solution written by some two-bit hack? I’d be far more likely to just scrap the whole thing and re-implement it (in this case, using the standard library instead), and then spend my time trying to find any broken code that depended on a specific, undocumented, and likely broken implementation.
The WHOLE point of comments is to make the maintenance guy’s job easier when he has to inspect your bug-ridden code three years from now. It is the epitome of narcissism to assume that the intent if your code can be understood from its perfect implementation. If you take the elitist attitude of “well, he should be willing to figure it out”, then you’re wantonly and deliberately wasting his time, and are a liability to your company.
on July 28th, 2008 at 5:18 pm
I agree that better parameter names are called for (like “tolerance”), and in general *if* the method is obscure, then sure. But it comes down to context.
For example, I don’t recall the last time I worked with somebody who hasn’t taken calc, so we all know Newton’s method, and calling it “Newton-*Raphson*” sounds pretentious and raises more questions than it answers. Would I comment things everybody can recognize? No, it’s condescending and wasteful. “P.S., ‘double’ here means it can hold a floating-point number”.
If you want to comment this function, say what it does in edge cases, or what its performance guarantees are. Those could actually be useful.
As for the “why”, for a method with no side-effects, that probably belongs where the function is used. A general-purpose function like this can be used many places, each for a different reason.
At this point, though, we’re getting bogged down in the details of a micro example. If we want to be picky, where are the unit tests for it? Those rank higher for me than even comments, because they show (a) how it’s to be called, and (b) that it at least works as the original author intended.
on July 28th, 2008 at 9:17 pm
Bah. Original poster is correct.
If you have to explain the awesomeness of your code verbally, your audience didn’t understand it. Check your friggin’ ego and add some comments.
If you pan out and think the resulting formatting is ugly, you’re missing the point. Go paint some pictures. Please leave the real coding to someone who understands why the most brilliant line of code absolutely sucks if it takes 4 people to figure out why it broke the new patch.
on July 28th, 2008 at 9:57 pm
I do disagree with you, but not enough to write an essay on why.
I usually refer to the C Kernel Coding Style’s chapter 5 when I decide how much to comment my code. Let me quote it:
“Generally, you want your comments to tell what your code does, not how.”
- This is why Jeff Atwood’s method name is correct. It tells the reader exactly what the code does, not how. If anyone is supposed to maintain that kind of code anyway, he’d pretty much have to know all common square root approximation algorithms. A comment would not help him very much at all.
on July 28th, 2008 at 10:14 pm
[...] No, your code is not so great that it doesn’t need comments [...]
on July 29th, 2008 at 1:01 am
@DoubleWhopper:
Thank you sir! That is exactly what I’ve been trying to say in a gazillion less words! What people are not understanding about this issue is not that we’re against comments. It’s that comments are being misused. If your code is well written I don’t need you to repeat what’s obvious by looking at the code. The only exceptions are the beginning of complex procedures (and this should be kept small and concise), and business logic. I don’t need a comment telling me that sqrtApprox() means square root approximation using newtons method, I’m being told it is by the procedure’s name and I’m being told how it works by the code in it. And I’ve read lots of comments, specially in Jeff’s post about catering to beginners. In response to anyone that thinks like that, kn ow you’re doing them a disfavor. Keep the endless commented code in books and in the whiteboards. People that code for a living should not have to carry on a beginners inexperience in production level environments.
on July 29th, 2008 at 5:31 am
[...] New Adventures in Software » No, your code is not so great that it doesn’t need comments (tags: cs) [...]
on July 29th, 2008 at 2:46 pm
- – - This is why Jeff Atwood’s method name is correct. It tells the reader exactly what the code does, not how. If anyone is supposed to maintain that kind of code anyway, he’d pretty much have to know all common square root approximation algorithms. A comment would not help him very much at all. – - -
There are 3 likely people who will be looking at the square root code:
1. An expert in square root algorithms who will recognize the code right away and fix the bug in no time.
2. A code maintainer who was thrown onto the project by management, and doesn’t know anything about square roots beyond pushing buttons on a calculator.
3. A developer who is using code that calls this square root function, and who is trying to figure out why it’s not giving the result he expected.
Of those three scenarios, 3 is most likely, followed by 2 and then a distant 1.
In this case, how hard is it to put in a simple comment? And why resist so vehemently against helping the poor guy who needs to get the bloody thing fixed as soon as possible?
/**
* Approximate the square root.
* @param n the number to get the square root of
* @param tolerance max distance between square root estimates
*/
private double approximateSquareRoot(double n, double tolerance)
{
// Newton-Raphson algorithm
double root = n / 2;
while (abs(root – (n / root)) > tolerance)
{
root = 0.5 * (root + (n / root));
}
return root;
}
That’s it. Not only are the function arguments documented, but with a single comment inside the code, all becomes amazingly clear.
on July 29th, 2008 at 4:02 pm
Wolter,
most IDE’s I have used will have a tooltip that pops up with the Javadoc etc when you are typing in a method name. If you have to include the algorithm name, and im not saying you dont, include it there.
/**
* Approximate the square root using the Newton-Rhapson Method
* @param n the number to get the square root of
* @param tolerance max distance between square root estimates
*/
private double approximateSquareRoot(double n, double tolerance)
{
double root = n / 2;
while (abs(root – (n / root)) > tolerance)
{
root = 0.5 * (root + (n / root));
}
return root;
}
but really that isnt ideal.
/**
* Approximate the square root using the Newton-Rhapson Method
* @param n the number to get the square root of
* @param tolerance max distance between square root estimates
* @throws InvalidArgumentException thrown if edge cases are passed that cannot be approximated
*/
private double approximateSquareRoot(double n, double tolerance) throws InvalidArgumentException
{
if(n == Double.NaN){
throw new InvalidArgumentException(”Cant approximate square root of Double.NaN”);
}
if(n == Double.NEGATIVE_INFINITY || N == Double.POSITIVE_INFINITY){
throw new InvalidArgumentException(”Cant approximate square root of Infinity”);
}
if(n == 0){
return 0;
}
double root = n / 2;
while (abs(root – (n / root)) > tolerance)
{
root = 0.5 * (root + (n / root));
}
return root;
}
Now do we really need any extra comments to tell us how the code will behave?
Why the hell is the code called instead of a system library? well that is probably a question for the calling code, and does not belong anywhere near my method.
on July 29th, 2008 at 4:56 pm
Of course, you’d most likely use a system library in the real world, but this example is just to illustrate a point.
Regarding comment location:
If you put the algorithm name in the header comments, then of course there’s no need to put it in the code itself as well.
However, you want to be careful about what you put in the public comments. It’s a lot like a contract. If you only specify WHAT it is doing in the public comment rather than HOW, then you can change the implementation later without breaking the expectations of the users of your function.
In this case, it’s probably not a major issue (not sure, since I know next to nothing about square root algorithms), but there are a lot of cases where specifying an implementation publicly could seriously harm a program that uses that code when you change the implementation later.
For a contrived example, suppose you wrote a sort algorithm with this header:
/**
* Sort an array of integers using qsort
* @param array the array of integers
**/
public void sort(int[] array)
Now if you changed it to use merge sort:
/**
* Sort an array of integers using merge sort
* @param array the array of integers
**/
public void sort(int[] array)
All would seem well on the surface, except for existing programs that assume qsort will be used and manage their data accordingly. Suddenly, they could find themselves having weird performance issues.
on July 29th, 2008 at 7:27 pm
@Wolter:
Why not include such comments?
// Approximate the square root.
- Why would you need this when approximateSquareRoot(…) is already telling you what this is?
// @param n the number to get the square root of
- I already know where getting a sqrt approximation. So I by default already now I need a number to get the sqrt of anyways. And if I need to make sure one glimpse at the procedure itself makes it obvious n is such number.
// @param tolerance max distance between square root estimates
- Tolerance is the limit of variation of a measure. You don’t need to be an engineer to figure that out. Hell, photoshop has a “tolerance” for the magic wand tool.
I don’t agree that comments are “not necessary”, but the whole argument some of us are trying to bring forward is that they are not a replacement for solid naming conventions, and the use of comments everywhere promotes bloat and, more than less, can make code harder to maintain.
An expert should have no problem reading this code. A code maintainer that doesn’t know anything about square roots beyond a calculator WILL need to google it anyhow because it’s not the comment’s job to teach him about square roots. A developer that needs to fix this code already has the info from the comments thanks to the naming convention. He’s gonna need to google square root approximation methods anyways to understand completely why the the procedure works or not.
on July 30th, 2008 at 12:48 am
Code comments should not explain the obvious. There needs to be extra meaning behind the comment itself – something not obvious from the code.
As a rule of thumb, if you the person can figure out in less time then it takes to read the comment then the comment should not be there.
http://www.codesplunk.com/?s=c
Programming Language Questions & Review
on July 30th, 2008 at 2:11 am
James:
The top comments were done in javadoc style. It’s more of a habit for me and not strictly necessary because, as you have said, we know from the names what it does, and “n” is pretty obvious as well.
I usually add in all of the parts of a javadoc comment for completeness sake so that when the html docs are generated there aren’t holes in the documentation, but I only add a javadoc tag for something that has at least one part that needs explanation (in this case, tolerance). Since it’s all up front, it doesn’t hinder readability. This is just the way I do things, and is not really a requirement in my book.
I remain firm in my stance on specifying the algorithm used, just as I’d ask for a description of a complex routine in any code. The comment specifying the algorithm is a pointer to the information required to know what’s going on in the code that follows, since the code is non-trivial.
There is absolutely NO need to learn all about square root algorithms to fix errors in this code. All the person needs to do is look up the specific algorithm used, find out how it’s supposed to be implemented, and look at how it actually was implemented. That’s more than enough to fix the problem. If the choice of algorithm is the problem (which is far less likely), then he can start looking up all the wonderful algorithms out there.
Case in point: I am an expert. I have 12 years experience spanning various spheres, businesses, platforms, and disciplines. I have built point-of-sale systems, medical instruments, engine control units, desktop apps, web apps, crappy 1-shot systems, 3-tier enterprise systems, mainframe batch systems and more. I have absolutely NO idea what square root algorithms there are out there, nor do I care, nor should I care. The point of these algorithms is that a bunch of smart PHDs have already done the hard work of finding out the best way to do things so that I don’t have to. I would be a simple user of the library, punching in numbers and expecting it to do its magic. Were I to find that the library is not giving the expected results, I shouldn’t have to spend hours/days researching square root algorithms just so that I can match one of the implementations to the one I found in the buggy library.
In fact, if I were to come across such a situation, I’d probably just throw the library away and go with something else.
I work in the real world. I have a job to do, and I don’t have time to fuck around.
on July 30th, 2008 at 5:09 pm
Comment Discontent…
There seems to have been a recent outbreak in blog posts about code commenting. As is so often the case with topics such as this, everyone has an opinion and they all seem to be different. It’s quite an eye-opener seeing some of the explanations,…
on July 30th, 2008 at 9:43 pm
Hi Dan, good points covered here as usual. I fully agree on the usefulness of the comments. What I want to see in the comments is more about the thought process of the developer. I want to know what were the requirements and the constraints and what assumptions were made at the development time. I also want to be warned about traps and side effects. As a result of this comments related discussion I decided to elaborate more on how bad comments are born at http://littletutorials.com/2008/07/30/how-bad-comments-are-born-in-your-code/
Thanks and keep the posts coming
on July 30th, 2008 at 10:40 pm
I agree with comments in your code. My thought is “explain how it works and what you are doing so someone else can come in and follow your train of thought”. Nice posting.
on July 31st, 2008 at 4:26 am
At work, most everybody I know complains that the code doesn’t have enough comments. But in my experience, debugging and maintaining code has always come down to reading through the code to try to pinpoint the problem.
I think having well written code is most important, with a minimal amount of comments to try to explain what the code cannot.
on August 2nd, 2008 at 1:49 am
[...] article is a response to: this blog. Comment away, so to speak. Filed Under (Best Practices, Java) by Derek Read [...]
on August 2nd, 2008 at 6:01 am
[...] No, your code is not so great that it doesn’t need comments [New Adventures in Software] – Dan Dyer gives some interesting points about why comments are necessary even for "self-documenting" code. I think of it this way: if 80% of the time your program is being maintained, you really need to make it as easy to understand as possible. True productivity means cumulative time saved and not just your time. [...]
on August 3rd, 2008 at 5:00 pm
[...] No, Your Code is Not so Great that It Doesn’t Need Comments by Dan Dyer [...]
on August 4th, 2008 at 8:24 am
on the flip side of things….
why commenting can be bad
http://w.holeso.me/2008/08/the-dark-side-of-code-commenting/
on August 5th, 2008 at 5:14 pm
[...] No, your code is not so great that it doesn’t need comments [...]
on August 5th, 2008 at 7:07 pm
Wolter:
“The top comments were done in javadoc style. It’s more of a habit for me and not strictly necessary because, as you have said, we know from the names what it does, and “n” is pretty obvious as well.”
- Point taken and I can see where you’re coming from.
“There is absolutely NO need to learn all about square root algorithms to fix errors in this code.”
“I have absolutely NO idea what square root algorithms there are out there, nor do I care, nor should I care.”
“I would be a simple user of the library…”
- I completely agree. There’s really no need for us (and I also consider myself an expert since I’ve been in the software development business for 10 years and have built countless, both crappy and exquisite, software solutions for varied companies in many different fields) to learn anything about square roots. I have no time for that either. You shouldn’t care, and I shouldn’t care either. But that dude that ends up maintaining exactly that piece of code we don’t even want to see ever, does care. Comments are not gonna be enough to instruct him on the proper method used in the code, unless you bloat the code with a copy paste from wikipedia between multiline comments. Nevertheless, a search for “approximateSquareRoot” will get the person to this blog and he’ll have all the info he’ll ever need about naming conventions and where to look for square roots explanations. If he searches for “approximate Square Root” he’ll get a webpage with this title “How to calculate a square root without a calculator” (and an explanation to rule over all other explanations on this particular issue); and a wikipedia page that explains the newtons method in a way simple enough to grasp what he needs to do.
“In fact, if I were to come across such a situation, I’d probably just throw the library away and go with something else.”
- So would I…
“I work in the real world. I have a job to do, and I don’t have time to fuck around.”
- So do I. And so does the guy that does need to maintain that code. For you and me, it means using another library. For the other dude, it means either reading this humongous comment on the code (and most programmers are not good at explaining things…. oh the irony), or googling the procedure name and actually finding everything he needs to know in a smaller more organized package.
on August 5th, 2008 at 7:30 pm
[...] recent posts Dan Dyer and Jeff Attwood took somehow different positions regarding what good comments are and if we need [...]
on August 7th, 2008 at 10:14 pm
[...] No, your code is not so great that it doesn’t need comments I like rants that tell you to comment your code. Just because you can understand the intention it does not mean that others will interpret the information in the same fashion. [...]
on August 8th, 2008 at 11:26 pm
I am just SO sick of the whole “I am a better programmer/coder/developer/etc than you because I think this way” mentality, that I could seriously puke on each and every one of you.
We all work our asses off all day doing something we love, and what do we get for it? We get some guy who, just because he has a web site which now a blog, thinking he is better/smarter/whatever and his senseless/brainless sheep followers who bitch because we don’t think like he does.
Just because you do something one way, doesn’t mean it is the ONLY way to do it. GET OVER YOURSELF and do something constructive.
on August 12th, 2008 at 12:36 pm
The why in comments needs to be used judiciously in my opinion. If you are creating object methods and, as you should as an OOP programmer, be considering re-use, the why is not necessary as this will change with each different implementation and can be seen as a limiting factor. Rather include the why into the method call than as a part of the actual method itself. That way you wont be editing (or forgetting to edit) the comment with each new implementation.
on August 13th, 2008 at 5:10 am
[...] Read the story This entry was posted on Wednesday, August 13th, 2008 at 1:03 am and is filed under le Chat Marchet. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. [...]
on August 18th, 2008 at 7:35 pm
hi man i know this is a C# but what is the >? i keep on getting an error in while clause.
I’m a beginner btw thanks
on August 20th, 2008 at 3:22 pm
The gt; is supposed to be a greater than sign. It’s messed up by Wordpress. I’ll see if I can fix it.