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.

[...] New Adventures in Software » No, your code is not so great that it doesn’t need comments (tags: cs) [...]
- – - 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.
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.
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.
@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.
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
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.
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,…
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
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.
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.
[...] article is a response to: this blog. Comment away, so to speak. Filed Under (Best Practices, Java) by Derek Read [...]
[...] 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. [...]
[...] No, Your Code is Not so Great that It Doesn’t Need Comments by Dan Dyer [...]
on the flip side of things….
why commenting can be bad
http://w.holeso.me/2008/08/the-dark-side-of-code-commenting/
[...] No, your code is not so great that it doesn’t need comments [...]
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.
[...] recent posts Dan Dyer and Jeff Attwood took somehow different positions regarding what good comments are and if we need [...]
[...] 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. [...]
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.
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.
[...] 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. [...]
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
The gt; is supposed to be a greater than sign. It’s messed up by WordPress. I’ll see if I can fix it.