I <3 Steve McConnell*
Coding Horror
programming and human factors
by Jeff Atwood

July 24, 2008

Coding Without Comments

If peppering your code with lots of comments is good, then having zillions of comments in your code must be great, right? Not quite. Excess is one way good comments go bad:

'*************************************************
' Name: CopyString
'
' Purpose: This routine copies a string from the source
' string (source) to the target string (target).
'
' Algorithm: It gets the length of "source" and then copies each
' character, one at a time, into "target". It uses
' the loop index as an array index into both "source"
' and "target" and increments the loop/array index
' after each character is copied.
'
' Inputs: input The string to be copied
'
' Outputs: output The string to receive the copy of "input"
'
' Interface Assumptions: None
'
' Modification History: None
'
' Author: Dwight K. Coder
' Date Created: 10/1/04
' Phone: (555) 222-2255
' SSN: 111-22-3333
' Eye Color: Green
' Maiden Name: None
' Blood Type: AB-
' Mother's Maiden Name: None
' Favorite Car: Pontiac Aztek
' Personalized License Plate: "Tek-ie"
'*************************************************

I'm constantly running across comments from developers who don't seem to understand that the code already tells us how it works; we need the comments to tell us why it works. Code comments are so widely misunderstood and abused that you might find yourself wondering if they're worth using at all. Be careful what you wish for. 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.

While comments are neither inherently good or bad, they are frequently used as a crutch. You should always write your code as if comments didn't exist. This forces you to write your code in the simplest, plainest, most self-documenting way you can humanly come up with.

When you've rewritten, refactored, and rearchitected your code a dozen times to make it easy for your fellow developers to read and understand -- when you can't possibly imagine any conceivable way your code could be changed to become more straightforward and obvious -- then, and only then, should you feel compelled to add a comment explaining what your code does.

As Steve points out, this is one key difference between junior and senior developers:

In the old days, seeing too much code at once quite frankly exceeded my complexity threshold, and when I had to work with it I'd typically try to rewrite it or at least comment it heavily. Today, however, I just slog through it without complaining (much). When I have a specific goal in mind and a complicated piece of code to write, I spend my time making it happen rather than telling myself stories about it [in comments].

Junior developers rely on comments to tell the story when they should be relying on the code to tell the story. Comments are narrative asides; important in their own way, but in no way meant to replace plot, characterization, and setting.

Perhaps that's the dirty little secret of code comments: to write good comments you have to be a good writer. Comments aren't code meant for the compiler, they're words meant to communicate ideas to other human beings. While I do (mostly) love my fellow programmers, I can't say that effective communication with other human beings is exactly our strong suit. I've seen three-paragraph emails from developers on my teams that practically melted my brain. These are the people we're trusting to write clear, understandable comments in our code? I think maybe some of us might be better off sticking to our strengths -- that is, writing for the compiler, in as clear a way as we possibly can, and reaching for the comments only as a method of last resort.

Writing good, meaningful comments is hard. It's as much an art as writing the code itself; maybe even more so. As Sammy Larbi said in Common Excuses Used To Comment Code, if your feel your code is too complex to understand without comments, your code is probably just bad. Rewrite it until it doesn't need comments any more. If, at the end of that effort, you still feel comments are necessary, then by all means, add comments. Carefully.

Posted by Jeff Atwood    View blog reactions
« Building Tiny, Ultra Low Power PCs
Understanding The Hardware »
Comments

I agree! Comments in code are a double edged sword; they're become like more code to maintain. And if no one is maintaining them, they become downright dangerous.

I use comments sparingly, and only to tell what's being done and how. Usually in the form of one-liners.

Jaryl Sim on July 24, 2008 7:03 PM

what the hell is a comment?

Calvin on July 24, 2008 7:29 PM

[quote]And if no one is maintaining them, they become downright dangerous.[/quote]

That's just job security. I'll do one better.. insert lies and comments that make no absolutely no sense.

Relax, I kid.. I kid..

Mike on July 24, 2008 7:30 PM

I've found, when looking back at really old work, that the comments were nothing more then psuedo-code typed before actually making things work.

When I look at my systems today, about the only comments I find (other then TODO stuff) are notes about the business rules being implemented by the code and even then only when the business rules are intuitively obvious.

For instance, in my current project I need week numbers. However, we base week numbers by starting from the last monday of the year before. That's weird enough to actually document as a method named "GetWeekNumberStartingFromLastMondayOfPreviousYear" is just silly.

I've heard arguments for using comments during maintinance to show what was tried, but frankly, if you're checking in your work on a regular basis, you already have that history.

Lucas Goodwin on July 24, 2008 7:30 PM

Hm, you should still have a comment in that code snippet stating it uses Newton-Raphson approximation, IMHO. And you definitely don't want that as part of the function name. Heck, even having "Approximation" in the function name might be putting too much implementation detail in the function name, unless you're dealing with a common code library that just *might* be picked up by engineering.

Oh, and you'd definitely also want some error margin information as part of the function comment... in case somebody from engineering even *considers* using the routine :)

f0dder on July 24, 2008 7:32 PM

r = n / 2;
while ( abs( r - (n/r) ) > t ) {
r = 0.5 * ( r + (n/r) );
}
System.out.println( "r = " + r );


Isn't (n/r) always 2?

alex on July 24, 2008 7:33 PM

> never, ever start with comments.

Unless it's inline extractable API docs like javadoc of pydoc, of course.

John Levon on July 24, 2008 7:37 PM

One problem with your example is that it's taken from numerical analysis, where knowing HOW the computations are made is essential to judging their accuracy for various inputs. Saying "This subroutine computes X" doesn't convince anybody that it's accurate.

Which brings me to your square-root example. Your final version tells me that the code approximates the square root. However, without a comment to tell me that Newton's method is being used, I cannot know this without spending time examining the code closely and having seen Newton's method in an algorithm before. Most developers would give up well before they make that realization --- forcing them to ask you to explain the algorithm and convince them of its correctness, which wastes more of your time than it would take to write the comment.

Michael on July 24, 2008 7:39 PM

The only problem with writing understandable code is that many programmers have no idea how confusing their stuff is. Sure, it's 20 pages of unorganized cryptic statements, but THEY understood it. Surely if someone else doesn't understand it, they must be lousy programmmers.

A. L. Flanagan on July 24, 2008 7:43 PM

I find that when I stub out a method, I pseudocode it first with comments. This helps me think through the logic and scope of the task and generates a roadmap that I can return to if I'm interrupted.

It seems to generate very useful comments for others to follow later.

BOB on July 24, 2008 7:50 PM

"never, ever start with comments"

I find I write my code cleanest when I start by filling in my methods with what they ought to do in comments, then filling in what they actually do after I've got my architecture down.

And, if I comment in the API doc style of the language, I get nice documentation to boot, as mentioned before.

Nick on July 24, 2008 7:56 PM

I couldn't agree more. When I was a junior developer I used to bemoan the lack of comments in code created by my more senior team members. Now that I am a lot more experienced, a lot of comments tend to clutter up the code and reduce the comprehensibility.

Generally, comments tend to be wrong, or confusing. In addition, there is a tendency to comment code that is changing, or complex. When that code is modified further, the comment becomes out of date, but the instinct is to leave the comment in "just in case". Before long, nobody knows what a comment means, or why it could possibly be there.

The best comments are like the ones shown in the article. Short and to the point. If you are implementing a particular algorithm, then say so (perhaps with a link to an article explaining the method), but don't overload the reader with useless detail that is covered in the code.

Gwyn on July 24, 2008 7:59 PM

"It's OK to end up with comments in your code, but never, ever start with comments."

Just as others, who have already mentioned it, I too write comments before writing a line of code, as a way of helping me think things through; and I see nothing wrong with that.

I find a lot of your blog posts useful for generating discussion - it's your frequent dogmatic conclusions that make me wonder if your head has grown a bit big...

Jason Bunting on July 24, 2008 8:07 PM

I think comments are important because most of the programmers actually out there working are pretty hopeless. I may be able to write well-structured, clean code but the rest of my team won't understand it because they're very inexperienced. However, they're all we have.

The same happened to me when I tried to open up DNN when I was new to ASP.net. Beautifully written code, not a single comment, full of bugs. I couldn't make head or tail of it.

Leave the comments on for all the people who aren't brilliant, tireless programers.

Dan on July 24, 2008 8:09 PM

I will side with the people who say that badly maintained comments are worse than no comments. Comments in the code *are* code and need to be maintained as such; but there's no compiler or interpreter to tell you about the dependencies.

My own code tends to be tersely commented at best; the one time I remember writing about 25 lines of comment for three lines of code was because those three lines were getting around a bug in Windows 3.1 and there was no URL I could point people at to read about it...

Wilson on July 24, 2008 8:16 PM

Most of my comments contain the url from where I stole the particular bit of code from. Tests explain things much better than comments can. "Talk is cheap. Show me the code."

Brennan on July 24, 2008 8:16 PM

> Just as others, who have already mentioned it, I too write comments before writing a line of code, as a way of helping me think things through; and I see nothing wrong with that.

Not quite the same thing, unless those comments stay in the code after you've written it!

Jeff Atwood on July 24, 2008 8:19 PM

> Your final version tells me that the code approximates the square root. However, without a comment to tell me that Newton's method is being used, I cannot know this without spending time examining the code closely and having seen Newton's method in an algorithm before

SquareRootApproximation(n, Type.NewtonRaphson)

Jeff Atwood on July 24, 2008 8:21 PM

You can save on writing comments by designing every piece of software around a concept of software factories vomiting objects but looking really understandable, by-the-book academically cool.

Or you can write compact code, based on well thought-out usage patterns, not some over-engineered ego-busting monster that compiles, runs but cannot be reused.

BugRree on July 24, 2008 8:23 PM

Key problem: some comments can't be expressed through functional decomposition.

I agree that algorithm and data structure explanation should be done largely through functional and OO decomposition and member and type naming, and that this is one of the big reasons why naming is so important, but there are other aspects to programming than call-tree decomposable algorithms and trivially modular data structures. Not all problem domains and corresponding solution abstractions are representable in a first-class way using the tools of structured programming and object-oriented design.

What about global[*] state changes that affect horizontal sections of code, rather than the vertically-oriented call tree of a functional decomposition? [* or local to a large object graph - functionally not all that different]

What about concurrent programming, where every cross-thread-visible operation is only correct when every possible relevant state of every other thread has been considered?

What about older programs written in older languages using older techniques - I'm thinking of IDE compilers written in C with extensive global state, discriminated unions and semantic field reuse across different stages, in particular (since it's my day job). A few comments go a long way in these kinds of situations - particularly since one doesn't have the luxury of writing it correctly the first time, even presuming that the right abstractions are available in any single programming language.

Code that has been maintained for decades generally doesn't have an immediately understandable gestalt such that it can be immediately refactored and rewritten more clearly, and in these situations comments are vital to help build up that gestalt, so that future refactorings can occur.

Motivating example: you've got a data structure graph that represents a parsed piece of code, and you've got to do manipulations, optimizations, debug info extraction, and code generation - and do it all as fast as possible with minimal copying and reallocation etc. Classes don't sit well with the requirements - you want to separate out your parsing logic, debug info, optimization, code generation, etc., rather than lumping them all into a single class. Each of those phases will want to annotate the graph for its own purposes, but those annotations can go away when the phase is done. You end up using discriminated unions or something similar, along with functional pattern matching or a visitor pattern, etc.

I can assure you that that code (and data structure types) will improve with the addition of a few comments :)

Barry Kelly on July 24, 2008 8:24 PM

I'll remember to do this but perl's plain old documentation is so cool.

j on July 24, 2008 8:25 PM

I too like to start with comments if I'm writing a new function that I'm not quite sure about. Otherwise I agree.

The other real problem I see is when people don't keep the comments up-to-date with the rest of the code. As the 'what' changes, the 'why' can change as well. It's frustrating when the code says one thing and the comments say another. Which one is right?

And if the code evolves in a way in which it becomes self-explanatory, then by all means, take the comments out.

Brian on July 24, 2008 8:27 PM

I wish someone would tell this to my High School and University programming teachers...

Sean on July 24, 2008 8:29 PM

Then the .NET Framework code must be bad because I have to comment my code just to document how the framework works. Why can't we just go back to COBOL? That code was perfectly readable.

Robert S. Robbins on July 24, 2008 8:34 PM

Well, lately I realized that starting to write code with comments doesn't help as much as starting to write code with unit tests first.

And that's why I like TDD.

Jon Limjap on July 24, 2008 8:39 PM

I think there's something to be said for starting with comments. McConnell gives a thorough explanation of why you should, in fact, start with comments before even writing code in chapter 9 of Code Complete 2.

In short, you start by roughing out the design of the function/method/whatever in pseudocode. Then you rework and refactor the pseudocode until it's as plain as day what you're doing. Only then do you write the code needed to implement the pseudocode. At the end of the process you've still got the pseudocode there to act as comments.

Why delete it? It certainly helps maintenance developers and is a great check to ensure you actually coded the routine you intended to code.

Anyhow, this is just a thumbnail sketch of why you should use comments. For a much better (and more persuasive) argument, check out McConnell's book. Every professional developer should probably already have a copy anyhow.

keith twombley on July 24, 2008 8:39 PM

I always try to incorporate both ideas in my code. For example, I would write the square root approximation function as
SquareRootApproximation(n)
//Newton-Raphson approximation
{
...
}

Paul Ritter on July 24, 2008 8:42 PM

> SquareRootApproximation(n, Type.NewtonRaphson)

That's just silly, Jeff. You are going to parameterize the algorithm in order to avoid adding one simple comment? You suggest making the function's interface - and possibly it's implementation - more complex to avoid a comment? That's what I'd call a coding horror.

I have to agree with Jason Bunting. Either that, or you are trying too hard to be controversial and drive traffic to your site.

David Avraamides on July 24, 2008 8:45 PM

I think to be more precise, your statement should be: comments must reflect and explain the code exactly, all the time.

I don't care going through a very long comment IF IT HELPS me in the end.

It's not wrong to start with comments. If you can't put to paper what you intend to do, how are you going to start coding?

astigmatik on July 24, 2008 8:59 PM

A time when comments are a great and wonderful thing:

Given

1. Code you didn't write, but need to visit briefly to fix a problem

2. You spend more time than seemed reasonable to figure out what the hell the code was doing, and it wasn't obvious

Drop a line of comment in with your discoveries so that the next poor sod who has to visit that code won't waste an hour of THEIR life figuring out what the heck is going on.

{ Before anyone mentions that it would be better to fix the crap: 1) in real life, you don't always have time to change code to be perfect, and 2) if you do have the time, rewriting code to satisfy an ideal isn't the best use of the limited number of hours in one's life, unless it will somehow recover some of those hours at a future date }

Nick on July 24, 2008 9:06 PM

You're way off the reservation with this one. :)

With the Newton-Raphson approximation comment,you knew which method of approximation was being used. There is no way your refactored method name is clearer than that

And I find junior developers hardly ever write comments.

Crimson on July 24, 2008 9:07 PM

Also, we need to end this myth that code is EVER as clear as well-written English. This is patently false 100% of the time (your Newton-Raphson approximation example as proof is insane :) ).

That said, if comments are explaining "obvious" code (for some definition of obvious),then it's probably not necessary. However, I've yet to be on a software project where *too many* comments/documentation/etc was an issue. I'd love to have that problem.

Crimson on July 24, 2008 9:13 PM

I'm going to have to disagree with you too, Jeff. Commenting before you code a method body serves to let you flesh out the method before you spend the time to write the code for it. This ensures that you write what you intended to write, as you have the comment to look back to if you get stuck. Extracting API documentation from your code comments is a beautiful, beautiful thing. That means actually putting API documentation comments in your code.

In a previous entry you complained about the verbosity of code, but today you're advocating it in order to reduce "unnecessary" comments? Something doesn't quite add up.

Jeremy Privett on July 24, 2008 9:22 PM

@fodder
i agree with you...
but may be because im just a junior developer...and im not being sarcastic :)
may be experience will make me realize what Jeff and Steve are trying to say out here...mind you Jeff's SquareRootApproximation(n, Type.NewtonRaphson) is very legible, but there are times when self explanatory function names are not possible. It just saves me a lot of *slog* with some intelligent comments(or for that matter, even some unintelligent ones)peppered here and there.

Selecting a lighter shade for comments in the IDE makes life a lot easier for me(replacing default dark green in VS2005 to a light blue) to avoid those huge huge blocks of comments from bugging you.

Jeff may be you post one on IDE color scheme. Since your post on consolas font has helped me a lot.

Samrat Patil on July 24, 2008 9:25 PM

I have to agree with David Avraamides up there about your approximation code.

I code primarily in PHP, and my site uses quite a few includes, so I have to comment to remind myself where certain functions/variables which are being called are located.

Will on July 24, 2008 9:26 PM

It's rather silly to see so many comments against comments...

Well written comments, or even well placed comments, can save lots of work.

Relying on procedure names to comment?

Steve on July 24, 2008 9:28 PM

I usually use the <remarks> section in c# to explain the why of a method if required.

Tim Yen on July 24, 2008 9:41 PM

I do not write many comments except for particularly arcane functions and classes. Sometimes, and Im sure Im not alone, I dont know exactly the best way about doing something but I figure a logical way of doing what I need done. It may not be the best (because I Was not aware of a built in function or a method used to arrive at said conclusion), but it works. However, it works in a very difficult to understand manner (well maybe its just me). This is where I throw comments in.

But quite frankly, Ive maintained code that had comments plastered all over the login scripts. Are you kidding me? First year college students understand login scripts, why the hell are people commenting all over the place?

Mostly I avoid comments, but then I dont use stupid variable names like $b (or var b or Dim b or whatever). Of course, I wouldnt use SquareRootApproximation either (probably sqRtAppx which is perfectly understandable to me).

Adam on July 24, 2008 9:44 PM

Too many or wrong comments = bad
so no comments at all = good? What? How about well written and maintained comments that explain what you are doing? (not how you are doing it)

arle nadja on July 24, 2008 9:47 PM

Comments are important, even though in many cases clearer coding does the trick instead. The idea of comments explaining the "why" instead of the "what" is nice, but I think I have an even more convincing argument in favor of comments, which runs as follows.

Code, clear as it may be and with the most elegant of naming conventions applied to it, can only ever document itself. That is, such rare self-explanatory code can only document what's there, never what's not there. What's not there is all the different (usually naive) ways the original coder tried to write the code your reading, that were wrong for some reason. The role of comments is thus to explain those inherently unintuitive cases were code isn't as simple as it might have been in a perfect world. All those hidden pitfalls owing to bugs, support for some legacy design or a 3rd party workaround; all those algorithms that were tried and were found imperfect for the job (that some smarty-pants newcomer may wish to retry on his first day unless warned beforehand); etc. In all these cases, information critical to understanding the "what" hides in the "what not", and can only be exposed by explicit documentation (e.g. comments).

Assaf Lavie on July 24, 2008 9:57 PM

I agree with you Jeff. At least that his example:

"SquareRootApproximation(n)"

is more than adequate. You may argue that if by looking at the code and reading the procedure name you should almost instanly find that you're getting squareroots and using an approximation method. The comment will NOT explain the why unless you write a huge comments that honestly defeats the purpose. If the person reading the code is not current with his/her maths... They'll end up looking it in wikipedia comment or not. The difference is that the people that will "see" the code at first glance wont lose their time. And the people that don't get it will end up in the same wikipedia page with the comment or with well named objects anyways.

James on July 24, 2008 10:02 PM

I have yet to run into to code which was too commented.

Jared Parsons on July 24, 2008 10:25 PM

'never, ever start with comments' .. what a load of bollocks. if more people started with comments that outlined what they were attempting to achieve maintenance would be a heck of a lot easier, and so would spotting their bugs.

While I agree that ideally you want to end up with self-documenting code, more often than not you're writing rubbish on the first pass. And, pragmatically speaking, sometimes, a first pass is all that it gets until you have time to go back over it. When you do have time to go over it, those comments might help you or someone else refactor more efficiently.

It seems more often than not that people don't write what they mean to write, so comments should help spot bugs and they act like a checksum. In a code review if someone spots the comments differ from the code, then it can be followed up on.

Or just be like everyone else and write code for yourself with little regard to others. Don't unit test. If it compiles it must works. Phooey.

Just because some people drive like idiots, do you ban cars, or do you punish the idiot?

chico on July 24, 2008 10:26 PM

> SquareRootApproximation(n)
> //Newton-Raphson approximation

Sure, this is fine too; I only listed my version as a counterpoint to "you must add a comment otherwise nobody will know what approximation you're using".

As I said in the post: "If, at the end of that effort, you still feel comments are necessary, then by all means, add comments. Carefully. "

> if more people started with comments that outlined what they were attempting to achieve

Again, this is not at all what the post is about. Unless those comments remain in the code after you've written the function. I'm tempted to delete that sentence because so many people are misunderstanding it.

Jeff Atwood on July 24, 2008 10:40 PM

> we need to end this myth that code is EVER as clear as well-written English.

Really? Most of the english I read online is anything but well-written. At least code *compiles* (or interprets, if that's your cup of tea).

Jeff Atwood on July 24, 2008 10:43 PM


James -

I disagree. If you are relying on a well-known algorithm, you should identify the specific algorithm. Look up "Square Root Approximation" in Wikipedia, and I see nothing about the Newton-Raphson method or anything that looks like it will match the code. If I read really carefully, I see a link to "Newton's Method", which in fact does match the algorithm here. That's only after wasting a huge amount of time reading other approaches which don't match the given approach.

IMHO, always default to descriptive method names for algorithms, and always include wiki-friendly (or dictionary-friendly, or old-school-encyclopedia-friendly) terms. Therefore:

NewtonRaphsonSquareRootApprox(n)

Or:

/**
* Newton-Raphson Square Root Approximation
*/
NRSquareRootApprox()

Some purists will say "too much implementation detail", but IMHO you want that implementation detail in there. If you change the implementation to a different algorithm, it is right and proper that you should have to visit every single use of the method in your codebase to make sure the new algorithm will work as well there as the one you are targetting. And, if it doesn't, you then end up with "NRSquareRootApprox()" and "ISRSquareRootApprox" when you add in an Integer Square Root method for greater speed in some situations.

The other option, adding a constant parameter identifying the specific method, IMHO, is more clutter. The algorithm is fundamentally different, and different methods to attain similar results may require additional parameters (ex, a max iterations parameter might make sense for one approach but not another). You also end up with either an enumeration specific to that one method, or an inability for the compiler to check the validity of the enum being passed in (ie, you have implemented NR and ISR, but not BSR; what happens when the BSR constant is passed in?) The enumeration and the code implementation get too far separated in all but the simplest of algorithms, and so will get out of sync.

Tom Dibble on July 24, 2008 10:44 PM

I used to believe that well-written code was self-documenting... then I started working with a lot of junior devs!!

My philosophy now is to comment almost EVERY line, explaining the business rules - I find it encourages the junior devs to think about what they are doing. (And if you don't enforce "comment every line" then (because developers are all lazy) then the comments drop down to zero very rapidly and you end up with no comments at all.)

For example:

'Get all the customers who live in this state
dim objCustomers As New Customer = Customer.GetWhere("State = 'VA')
'If there are no customers in this state...
if objCustomers.Count = 0 Then
'... then we warn the user
MessageBox.Show("You are ALONE!")
End If

Yes, the comments are strictly unnecessary but they may help someone's understanding at some point in the future, and they certainly help mine when I am code reviewing, so... they stay!!!

Syd on July 24, 2008 10:48 PM

(Has Jeff jumped the shark?)

If you're saying that comments are useless if they are no clearer than the code, that's not exactly a revelation.

If you're saying that "well-written" code is always clearer than a comment, that's bo11ocks.

Comments are as much "note to self" as to anyone else:
1. I'm maintaining some code, it references some class. The code for the class is three pages long, but I just want to know what the class is there for. Shame that the guy who wrote the class (was it me?) considered that the code was self-explanatory.

2. I have a constant K_WIDTH=100. Cool, the coder was clever enough not to name it K_W. But why not 200?

3. Pushed for time, I haven't had time to refactor as I would have liked. How about a little //TODO? (Or //HACK?)

4. I'm maintaining some code, there is a 10-line procedure which could be replaced with just one method call. I think. Did the guy who wrote the code think of it? Is there some good reason to use 10 lines that I haven't seen?

5. (In C#) If I prefix the comment for my class or method with ///, hey, any client code gets extra information in intellisense. (That's even more useful if all they've got is the dll and no 'self-evident' code!)

6. I have a for loop with 5 method calls inside. Do I have to go and look at the code for the 5 methods to work out why the loop starts at 1 instead of 0?

OK, so all my examples are probably more why than how. My point is that you can ignore comments that *are* there, but you can't read comments that *aren't* there. Please don't give any extra ammunition to the 'write-once, read-never' cowboys coders who are just too lazy to make the effort.

How about you give us some examples of good *and* bad comments?

Ben on July 24, 2008 10:49 PM

I read english a hell of a lot quicker than I do code, give me a well written comment any day. And sure, give the method, variable whatever a descriptive name but don't skip the title. CamelCaseIsn'tThatGreatToRead.

Sam Hill on July 24, 2008 10:50 PM

PS - And, yes, I still enforce Hungrarian (sic!!) notation - otherwise (especially in case-insensitive VB) you end up with variables called the same thing as your classes, which ends up VERY confusing, especially if you use static methods a fair bit.

Syd on July 24, 2008 10:51 PM

Ok, here I go disagreeing with you guys.

These points reflect what would be done in an ideal world. And 2 years ago, I would agree with everything said.

HOWEVER, after working on a Monster of a project for the past two years, I've began yearning for comments in code. A lot of my work deals with bug fixes in existing code and I've finally quelled my urges to simply rewrite crap that doesn't work. Here are my reasons:
- Sometimes past developers were just simply bad and there's no 'time' to refactor.
- Significantly modifying (and trust me, a lot of the modifications needed would be significant) would require retesting that functionality in the QA department. In an environment where time = money, that just isn't a viable option.
- Comments are usually frowned upon where I am ("They get in the way", I've been told). So the alternative is to sit (sometimes for hours) debugging trying to figure out what's going on.
- In my environment, the 'weird' parts of the code usually deal more with business logic and less with actually functionality. When there's a statement that says: {if A = 'CPTY'}; I'm sorry, I need a comment. Because walking over to the support department to ask "what's CPTY" isn't my idea of the best use of my time.

So, what does one do with messy code when refactoring isn't an option? I say, comment the hell out of it.

Baz L on July 24, 2008 10:54 PM

You've incorrectly asserted that too many comments are bad, as evidenced by a large chunk of useless comments. Useless comments that add nothing to the code are just that, useless. But for complex methods that take several individual tasks, I like to start out by commenting what those tasks are. When I revisit my code, I can simply read the comments to see a breakdown of each step and what I was thinking at the time, without having to ever look at actual code.

Sure, a simply for loop extracting a value from a bean and placing it in a hashtable is pretty simple to understand if you're not uses cryptic variables, but I just can't see that
//loop through bean and place value in hashtable
isn't still adding value.

John Grimes on July 24, 2008 11:02 PM

I once saw a comment "confused" in one of tha web applications I support!!

Took some time to realise that this guy who wrote the code years back was refering to "XML messages sent to confused.com"

Shoban on July 24, 2008 11:12 PM

You're a year late Jeff...

<a href="http://www.clanmonroe.com/Blog/archive/2007/06/04/commenting-your-code-is-bad.aspx">http://www.clanmonroe.com/Blog/archive/2007/06/04/commenting-your-code-is-bad.aspx</a>

Jason Monroe on July 24, 2008 11:13 PM

> r = n / 2;
> while ( abs( r - (n/r) ) > t ) {
> r = 0.5 * ( r + (n/r) );
> }
> System.out.println( "r = " + r );
>
>
> Isn't (n/r) always 2?

There's a while loop there. In successive iterations r will be something other than n / 2 so n/r won't be 2 any more

Gareth on July 24, 2008 11:14 PM

- Tom Dibble

Yeah the Newton-Raphson method is generally called just the Newton method. I agree in some cases it's best to append a comment explaining a little bit of what's going on. But what I meant is also something you proved yourself. If I see SquareRootApprox(n) and I know that Newtons method is the most common for approximation of square roots, then I don't need to look any further into it. But if I see SquareRootApprox(n) or // Newton-Raphson Square Root Approximation, and I don't know what it is or the specifics of the algorithm and I type either in google... I'm gonna end up reading the same thing. The only other possibility is that the programmer inserts a comment as long as a blog post explaining how the Newton method works... and that just makes everything bloated and hard to maintain.

My issue with comments is that too many comments makes everything "uncomfortable" and a hell of a lot harder to maintain. I've been in situations where I have a file maximized on my 30 inch monitor and I'm looking at huge blocks of comments and 2 or 3 lines of code. I ended up removing the superfluous comments and rewriting a big part of the code. Nevertheless, when we got new developers on board, everyone got up to speed fairly quickly and everyone praised the naming conventions and wise use of comments in the code (which where probably less than 1% of the total lines of comments previously there).

James on July 24, 2008 11:15 PM

Not sure if you inspired this, or if it's just a coincidence but it's a comic that seems kinda relevant to the discussion: http://geekandpoke.typepad.com/geekandpoke/2008/07/good-comments.html

Todd McKinney on July 24, 2008 11:23 PM

I pretty much only use comments in two circumstances:

1. When what I'm doing in the code seems to make no (or not enough) sense. These tend to be either things like "If you don't do this way up here, you get an Off-By-One error" or else large blocks explaining that some object's implementation is brain-dead, must be worked around, and ending with "Thanks a lot, [object vendor]". Usually [object vendor] = Microsoft, but Crystal Reports has been a suspect in the past.

2. XML comments intended for Intellisense consumption. This is a recent development for me and I'm still wary about it.

Atario on July 24, 2008 11:43 PM

comments are merely words.

Jin on July 24, 2008 11:49 PM

It’s easy to make the same mistake with your user interface.

“Oh, this interface is a bit confusing. Let’s put some explanatory text in so that users understand what’s going on.” FAIL.

Paul D. Waite on July 24, 2008 11:50 PM

Pi is exactly three!

Trevor on July 24, 2008 11:51 PM

@Atario - 'XML comments intended for Intellisense consumption. This is a recent development for me and I'm still wary about it.'

Are you taking the piss mate, or were you just asleep for the last 7 years?

roflmao on July 24, 2008 11:55 PM

"never, ever start with comments" ??
I do it all the time for almost 20 years now. Worked pretty well so far.

Holli on July 25, 2008 12:17 AM

Ok, I'm pedantic. Maybe the last line of the refactored code should pass n as the parameter, rather than r.

System.out.println( "r = " + SquareRootApproximation(n) );

I love the Refactor menu in eclipse - it saves problems like this.

John.

John on July 25, 2008 12:18 AM

"It's OK to end up with comments in your code, but never, ever start with comments." - I guess this line was edited out? Cos I can't find it in the article. Good thing too.

Andrew on July 25, 2008 12:27 AM

Comments are great. Take another step.

Use GhostDoc to automatically generate comments for methods (a short description with parameters, if your function has a good name, also the comment is quite good too). What do you do with this comments?

Next Step: Use Ndoc to create an html Helpfile for your Code on basis of the comments.

Next step: automate the process so that you can have a daily helpfile for your actual code. Fast to browse with keywords for new developers.

A good thing is, that if you name your classes and methods correctly you can see in the comment quite good results.

Two examples of auto generated comment
E1
/// <summary>
/// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
/// </summary>
/// <param name="x">The first object to compare.</param>
/// <param name="y">The second object to compare.</param>
/// <returns>
/// Value Condition Less than zerox is less than y.Zerox equals y.Greater than zerox is greater than y.
/// </returns>

public int Compare(Object x, Object y)
{
if (x.Weight == y.Weight)
{
return 0;
}
else if (x.Weight < y.Weight)
{
return -1;
}
else if (x.Weight > y.Weight)
{
return 1;
}

return 0;
}
E2
/// <summary>
/// Handles the RunWorkerCompleted event of the backgroundWorkerPoll control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.ComponentModel.RunWorkerCompletedEventArgs"/> instance containing the event data.</param>
private void backgroundWorkerPoll_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)


You just need to add on or two lines yourself to get a code documentation. Really needed at big projects were each code is reviewed.

(The next tool in line would be something like FXCop to see if your code follows the company rules)

offler on July 25, 2008 12:29 AM

I believe comments are vital for explaining _what_ you're doing and _why_ if it's not _INSTANTLY_ clear. That is, even if your routine is understandable after a minute of thinking the code through, it needs a comment because it's not immediately obvious.

In your example, I agree that you should make that its own routine for clarity, but I still would have left the reference to "Newton-Raphson approximation" in there, no matter how you organised it. You cannot possibly believe that everyone will immediately understand that's what it's doing.

I like to think of the comments as integral to the "story of the code" - Combining the code and the comments, you can see what a routine is doing very, very quickly, and that's important.

Comments are the "what" and "why" of the code, and the code itself is the "how". When properly used, they slot together perfectly and have the ability to speed up development and debugging.

Comments at the start of methods and classes are possibly the most useful comments out there - they reduce the need for heavy commenting within the code itself, explain who did what and why (useful for corporate coding and maintenance), and when you combine them with something like doxygen it can save you a lot of time hunting down someone else's code in a large code-bed.

In my experience there are developers who comment and like comments, and developers who have never given comments a proper chance and therefore hate it. Often developers take on a level of arrogance that says that their code is so perfect they don't need comments, but you cannot forget that there are developers out there at all skill levels and if you really are a hot coder, most of those guys really won't understand why you're doing something in a certain way.

BTW, some of us are forced to go through code reviews with idiots who are not coders, such as IT auditors and management. With the comments, they can get by without you having to sit there painfully explaining every line to them!

Give comments a chance mate! If they're not working for you, then your comments are BAD comments!

Simon Butcher on July 25, 2008 12:41 AM

Yeah. I've already talked about it: (but in french)
http://sexycoders.com/index.php/2008-03-13/pourquoi-ne-pas-commenter-son-code/

Onur on July 25, 2008 1:06 AM

I think that comments are generally a good thing, as someone said about you can ignore the ones that are there but can't read the ones that aren't.

On my daily job I usually have tight deadlines that become tighter near the end, and that makes the code quality start to decay plus I have juniors on my team, so comments are a must. For example I just wrote:
//find cases in where this solution is relevant
//note: Last minute change, may be changed to backend at a later date.
protected function inferRelatedCases(solution:SolutionVo):String

This is not only a note to myself but also for someone in the future that comes across my code and wonders why this is here.

pedro on July 25, 2008 1:33 AM

Sorry to say this, but: You seem to produce more coding horror yourself than you try to prevent other from making.

Advocating not to comment your code is really not helping. Not helping at all. I have seen so many functions, classes, methods and other stuff whitout comments, where I had to read it line by line to figure out what it was supposed to to.

Of course, in such a simple example as you have given, you can probably name the function/method appropriatly to document it. Of course you should always choose self-documenting names for all symbols in your code. But in general, it is impossible to document every aspect of a class or method just by naming it right. The name can give you a general direction what it _might_ do, but in the end, you just _have_ to document all its parameters, side effects, restrictions, error conditions and everything someone who uses the code could need to know.

Of course it has to be maintained, but its just part of the whole process. You have to maintain a user manual too if you change functionality or add a feature. You can not just say: Hey, I named that button or menu really well, so I doesn't need to be documented anywhere. Again, this is true for simple cases ("OK"), but not in general.

Jeff, I urge you to rethink your approach here and not to advocate this any further. Try to think of the general case not just the simple ones (this applies to a lot of examples you have used in the past).

Simon on July 25, 2008 1:35 AM

Weirdly, your post started out making a very valid point (tell us why the code is doing what it is, not what it is doing) but then you proceeded to argue an entirely different point about why you should refactor your code to make it is more clear what it is doing.

So great, the new refactored code makes it clear that you're doing a Newton-Raphson approximation to the square root. But I still don't know WHY you're calculating a square root, or WHY you chose the N-R method (efficiency, accuracy, something else?).

The important comment here would be something like:

// using the N-R algorithm as it typically converges quickly
// to approximately the desired root. we don't need the exact
// value here because {reason} so this gives us better perf.

Greg Beech on July 25, 2008 1:36 AM

Sorry for the double post :( but here's an example of what I mean. Here's a method that removes a subscription in a catch block, taken from our real codebase. It is very obvious as to what it is doing, but do you know why?

this.Unsubscribe(subscription.Id);

Now does this comment help?

// if the operation was invalid when we know the cause must be an invalid workflow queue and/or the workflow
// not existing because the only other cause from the methods in the try block is that the workflow runtime
// is not started, and that can't be the case here as we just checked. as we'll never be able to deliver the
// result to a non-existent queue/workflow then we need to remove the subscription otherwise it will stay in
// the pending work queue for runtime services that persist their jobs and cause the service to enter an
// infinite loop processing work items that it can never complete
this.Unsubscribe(subscription.Id);

Greg Beech on July 25, 2008 1:41 AM

As far as I understand the re-written code, it doesn't work.

't' is never declared.

Unless it's a global? And I know someone as precious as this about a simple thing like comments wouldn't go around advocating a global.

GunstarCowboy on July 25, 2008 1:41 AM

I find I put one or two comments in as I am working on a couple of methods then when I refactor sometimes they become unnecessary. Once I have got to a stopping point like written a set of methods or a full class I will have a quick scan through adding in some more general comments about what a method does if it isn't apparent in the methods name.

Don't comment with pseudo code most programmers can read the actual code easily. A comment should be a sentence covering what a set of lines do so you can skip them when debugging if you know they work.

pete on July 25, 2008 1:50 AM

My first thought on reading the post title was: comments are not to be messed with.

But after reading your and Sammy Larbi's posts I took a look at my more recent code... and realized you guys are right. I still think complex code needs comments, but as you choose descriptive names for your methods the code should be self explanatory.

Posted an example of my own code on my blog: http://www.markvandenbergh.com/archives/21/no-more-comments-in-your-code/

Mark on July 25, 2008 1:50 AM

> I haven't added a single comment, and yet this mysterious bit of code
> is now perfectly understandable.

Actually, no. I *still* have no idea what the hell that algorithm is and why it works. OTOH, "// square root of n with Newton-Raphson approximation" tells me all I need to know in order to be able to find more information about the algorithm, should I need it.

xxx on July 25, 2008 2:01 AM

Agree 100%. If you can't tell what the code does without comments, the code isn't done yet.

Kevin Dente on July 25, 2008 2:03 AM

Whats a comment? Whats "documenting"?

My 10 bits.

Comment as a prototype of the code, just to get my idea of the code out.

Replace the comments (not underneath) with the code, often being a meaningful method name.

Add comments to highlight any "quirks", notes, methods used, reasoning why. e.g. "Uses X method to do some awesome sh!t to the string", "This code is sluggish, but I cant think of a better way, tried x,y,z".

Rob on July 25, 2008 2:06 AM

Comments are for anything unusual in my books.
Anything that isn't immediately obvious or would look a bit "wrong" without a comment. This means that they describe either some form of hardware or architectural limitation, a fixed bug, some performance hi-jinks or a curious customer requirement.

Oh I also use them to explain to readers that i've considered certain code paths and am happy they do nothing.

if(blah)
{
blahblah
}
else if(blah)
{
blahblah
}
else
{
// do nothing
}

Jax on July 25, 2008 2:13 AM

Well, I partly agree... and then I disagree again. First of all

COMMENTS ARE GOOD!

Never think otherwise. Trying to avoid comments is a step into the wrong direction. It's not about avoiding comments. It's about getting your comments RIGHT(tm).

As other people pointed out, by choosing the right name for the function, you made clear, that this function calculates a square root. But you don't tell people which method it uses and why you chose this method.

This gets me to the point:

1) Don't use comments to tell people what you are doing, unless it is very hard to see that by just looking at the code. Always assume that whoever will read your code is a good programmer and knows the language your code is written in quite well.


Most useless comment I have ever seen:

// Increase i by one
i++;

<sarcasm>Wow, thanks for the comment. Without it I had never guessed what happens there!</sarcasm>

If somebody needs a comment to know what i++ does, he shouldn't be reading this code in the first place.

But your square root example is a good example where I would leave the comment, even if you chose the function name to be more obvious, the name does not reflect which method you use for calculating the square root. I had at least written that as

private double SquareRootApproximation(n) {
// Using Newton-Raphson approximation
...

2) Always use comments to tell people WHY you are doing something.

The "what" might be obvious by just looking at the code, the "why" certainly never is. How can it be? The why exists only in your head. It's a design decision you made while writing the code and maybe not even you yourself will know 3 years later why you made it that way and not any other way. So make sure the "why" is either always obvious (because it's trivial) or add a comment that explains your design decision.


3) Don't over-comment.

I guess that was your main critics here and I totally agree with you. A lot of code has more comments than actually code. If that happens, something is wrong. It's highly unlikely that 100 lines of code are so complicated, that they need 300 lines of comment to understand them.

If you really implemented something so ingenious, that you want to share your cleverness with the whole world, write a 50 pages PDF file, upload it somewhere on the web, add a two line comment to your code that contains a link to it. Who really cares for a long winded explanation of what this code does, why it is so cool, a proof that it really works, a performance comparison, and so on, can grab that PDF and read it. For the rest of us, just add a comment what the code does, why you decided to do it that way and that it is really great - we will believe you ;)

Mecki on July 25, 2008 2:27 AM

Whilst I don't like essays as comments I still think adding that one line tidbit you'd added is useful.

// square root of n with Newton-Raphson approximation

Don't get me wrong, I'd still probably stick it as some sort of static method in a utility class somewhere but I like to know a little about the logic being used, and I think it becomes more relevant with more complex examples.

As an example this week I was working on some code to calculate the distance between spherical coordinates (lat, long), for my purposes I decide that the haversine formula - with a rough error of 3m for every km - was suitable. To me putting in something like

// haversine formula - error margin 3m per km

makes sense. Any other developer would be able to see it's limitations and determine if this was suitable for their needs.

MarkM on July 25, 2008 2:37 AM

Holy crap, is this bizarro world? Programmers are writing TOO many comments? I've never heard such a thing! I wish this was in line with my experience.

Just because I am a programmer and I can read code, does not mean I should have to. I'm not a compiler. Sure, I completely, 100% agree that code should be self-documenting where ever possible. On the outskirts of code, you will likely have some type of controlling logic which creates objects and calls functions, all of which should be fairly self-documenting and the flow is obvious and beautiful. These are the trivial cases. But as you get deeper in the meat and potatoes of the code, it becomes harder and harder to understand the code as immediately as the trivial parts. Instead of reading the code like a book, you have to start parsing the code like a compiler. It's inevitable. Not everything can be broken into a 4-line function with a nice name. In these cases, a simple "// XX does YY and then ZZ" makes all of the difference in readability. Not only that, but it shows the programmer's intent. If there happens to be a bug in this area, I can identify what the programmer was _trying_ to do, why her assumptions were wrong, and thus fix the bug. Self-documenting code is completely worthless if it's inadvertently documenting the wrong thing.

Really, the issue here, is the maintenance phase of the programming life cycle. As we know (From Facts and Fallacies), the maintenance phase consumes 40-80% of the total costs of a project. And maintenance programmers spend 50-60% of their time deciphering the code they are maintaining (Code Complete, referencing another source). So the question is, do comments help this "deciphering" phase? Yes. They do. They help more than not having them, that's for sure! I'd rather have too many comments than not enough. I think it's plainly obvious, but I'm sure there are studies that support it. Here is one with a few seconds of google searching: hxxp://csdl2.computer.org/persagen/DLAbsToc.jsp?resourcePath=/dl/trans/ts/&toc=comp/trans/ts/1988/09/e9toc.xml&DOI=10.1109/32.6171

Any time you have code that is going to need published documentation, JavaDoc-esque systems do take a lot of space comment-wise, but if you need to maintain documentation anyways, it's easier to do it right there in the code. It just takes a bit of discipline to remember to update the doc block if necessary whenever you are doing something in the code. Much more convenient than maintaining documentation elsewhere. And it may be useful to other programmers looking at the code, too.

It seems like there are a lot of posts on this blog and associated blogs with the tone of: "<Generally accepted good thing here> is actually TERRIBLE!!! OMG!!!". This is reminiscent of cable news network scare tactics and nonsense to start controversy when there really shouldn't be any. Yes, using comments, design patterns, regular expressions, XML, etc to the _extreme_ is bad. Of course. This could be said about anything. But what should be known is that they are generally _good things_, but should be used correctly, with care, and under the appropriate circumstances. Self documenting code and comments are both things a programmer should use and continually attempt to get better at.

Preaching the correct way to use these things is probably going to be much more helpful for those you are trying to address. I see that you aren't saying all comments are bad- But that is certainly the tone. It's not until the last sentence that you admit there may be a use for them. I think people like you, Sammy, and others currently on an anti-comment binge are only going to hurt yourselves if you are so strict and unwavering in regards to code commenting.

The effort it takes to write them is _vastly_ (and I mean VASTLY) overstated and the space it takes up on your screen an irrelevancy, as far as I'm concerned (Ignore the dark-green text!). You act like a programmer needs to be a novelist to write simple comments. I think I've seen people have a harder time naming functions appropriately.

In short, I don't think you are young enough to be so idealistic :)

SB on July 25, 2008 2:39 AM

It's not possible to overcomment something in reality.
This is another one of those bull$hit macho, 'I don't need comments in MY code' threads that should become ignored.

Jeff, why don't you go and re-read one of your favourite books, the Mythical Man Month, to hear all about this discussion and why you are wrong?

Paul Hollingworth on July 25, 2008 2:45 AM

Another related issue is use your source code control and don't use comments as a kind of historical record of code that has been replaced. It works for a couple of iterations in case your refactoring broke something - maybe - but 20 iterations later it's plain dangerous.

Be brave, delete stuff and trust in your source code control system.

Francis Fish on July 25, 2008 2:55 AM

But I like telling myself stories as I wrote code! Honestly, the layman's-terms expression of the function of whatever I happen to be developing is actually helpful, I've found, in keeping my own thoughts straight. So while I might have 4 times as many comments as you might recommend, I feel like my development process has been smoother and less convoluted. It probably helps solidify new concepts too.

However, before I hand my code over to another developer, or particularly before I deliver it, I strip out all my 'note to self' comments and rewrite things a lot more sparsely. It's kind of redundant, I know, but it works for me, so I figured it'd be worth mentioning.

matt on July 25, 2008 3:04 AM

What about when you're in a real world situation and you've just got to make a deadline? You can't begin to refactor your code for ten times, you've just got to get that shit out of the door.

J on July 25, 2008 3:06 AM

bool comment = false; // indicates whether this comment is required

Steven Bey on July 25, 2008 3:12 AM

Seems to me that everyone who is advocating writing comments in code are doing so from a point of view that code is difficult to understand.

My view, is that if well written (and that is important) code is hard to understand then it needs a comment. But if bad code is hard to understand it needs to be refractor.

And refactor is not the same rewriting (as it seems a lot of people seem to think). Refactoring implies 'no change in functionality' and therefore should have the same regression testing requirements as "slapping on a comment" (which is after all still a change to the source file).

Commenting badly written code (instead of refactoring it and correcting the 'badness') just propagates the problem further down the line to another person who will have to read both the comment and the code later.

Ron on July 25, 2008 3:17 AM

<Self-documenting code is completely worthless if it's inadvertently documenting the wrong thing>

Self-documenting is by definition the right thing. It may be poor code and wrong, but it is the correct documentation.
Comments rapidly become out of date with refactoring, and with fellow programmers not updating it.

// Newton Raphson method
private double SquareRootApproximation(n) {
(some other algorithm)
...
}

Writing tests before code documents the requirements by defining the inputs and outputs. No code comments required.

Also, why are you reading the code if you don't know why or how you got there? Junping into the middle of a program without an aim is pretty pointless.

Aaronrs on July 25, 2008 3:20 AM

this post reminds me of the NeHe OpenGL tutorials, where every single line, including opening and closing braces are commented.

Comments in my code are just that - comments; little side notes, kind of what you'd note down next to someone else's code if you were tring to work out what it did.

And if you hate giant comment blocks, don't view source that's been formatted for Doxygen.

James on July 25, 2008 3:29 AM

If you're doing Newton-Raphson, I hope you're doing so for a reason other than demonstrating your Mighty Math Muscle. State that you're using this algorithm, and why. State the accuracy bounds, and enforce via tests. Don't leak implementation detail in the interface.

Jeff's "SquareRootApproximation(n, Type.NewtonRaphson)" examle is bad for reasons already mentioned, it's clunky, and depending on language+compiler might generate suboptimal code. If you're doing N-R it's usually because of speed concerns, so you don't want suboptimal.

I do fully agree you shouldn't comment every single line, though, and maintenance coders not updating comments *can* be a problem. But would you want a maintenance coder on your team who changes algorithm without updating comments? Chances are that coder won't be writing proper tests, either.

As for "Junping into the middle of a program without an aim is pretty pointless." - debugging other people's code, perhaps? :)

f0dder on July 25, 2008 3:31 AM

It's reassuring to read the replies and find that so many people don't buy the "less comments are good" nonsense.
There are two main reasons that lead to this incorrect thinking:
1. Developers think that code tells you "what" is being done and comments should tell you "why" it's being done. This is nonsense. Code tells you "how" something is being done, and comments should tell you "what" is being done on a semantically richer level than instructions intended for a machine. Even better if they also tell you the "why".
2. Developers regularly overestimate the self-explanatory power of code they have written themselves. It's only experience that teaches them to take nothing for granted. Please don't tell inexperienced programmers that comments should be avoided.
I agree, however, that writing good comments requires good writing skills that many coders do not possess. Again, it doesn't help to reassure these that comment-free code is good, because without practice, they never gain the necessary skills. In my opinion, comments and code intimately belong together and should be improved together.
By the way, I think that programming skills correspond with writing skills on a very general level. Bad writers confuse ideas, present them incoherently, get character traits wrong, use inconsistent naming, grammar and punctuation, and tell their stories in an unimaginative, boring and sloppy way, not detecting mistakes and limiting story development through these errors. Bad coders confuse and misunderstand requirements, structure code incoherently, get abstraction levels and data structures wrong, use inconsistent naming, idioms and punctuation, and sloppily implement algorithms that are unimaginative, inefficient and buggy, limiting maintenance and enhancement possibilities. I believe that good programmers are mostly good writers and vice versa. As a corollary: Most software is buggy, inefficient and hard to maintain because their authors suck at writing.
You could go a long way in telling people how to write and code correctly, Jeff, and improve their coding abilities. For my part I'd look forward to again read an inspiring post from you. It's about time.

Leo on July 25, 2008 3:32 AM

Apprentice: either writes comments, lots of comments or writes incomprehensible code with no comments.

Journeyman: writes self-documenting code with no comments.

Master: Writes comprehensible code that is commented where doing so enhances understanding.

Something like that?

Mike Woodhouse on July 25, 2008 3:36 AM

> For my part I'd look forward to again read an inspiring post from you

Do I really need to write a post saying "comments are good, please use them?" That's like writing "code is good, please write it."

http://www.codinghorror.com/blog/archives/000878.html

If the best code is no code, what is the best comment?

> Apprentice: either writes comments, lots of comments or writes incomprehensible code with no comments.
> Journeyman: writes self-documenting code with no comments.
> Master: Writes comprehensible code that is commented where doing so enhances understanding.

+1

Jeff Atwood on July 25, 2008 3:44 AM

Couldn't agree more about the thrust: comments should be used sparely, and code should document when at all possible.

But let's face it -- anyone replying to this post is part of the 5% of programmers who actually give some thought to the topic while working.

It's the other 95% that's the problem.

John Pirie on July 25, 2008 3:46 AM

What the hell???

Instead of adding a single line of comment, you recommend writing the stuff as a function/method, and comment it by giving this function a speaking name - even though the code is onl run once, and no function is necessary(otherwise it would be there anyway)?!

Sorry, that's not real affective, and will, for all those morons that make other developer's day hard by not being able to give functions a decent name, not make anything better.


And then the "You should always write your code as if comments didn't exist.".

Totally mislead - as when you're walking along the equator to find th north pole (not as wrong a s on the south pole, but here, not even the temperature is right...)

I code by writing the comments first - saying in human language, what I'm actually about to do, and, by that way, realizing problems in things because I have problems to describe them - so, before the first line of actual code is written, I realize problems in my spec(if such thing ever exists - in real life you don't get these so easily).

When I write unit tests, the first thing I do is try to write "prerequisites" and "expectations" into the comment above the code - before starting to write the test. As with the coding itself, it makes me reassure, that I have enough inside in the problem to be solved so I can describe it in a short sentence - if I'm lacking this, I will never be able to write a decent line of code doing these things.

Even though I don't want to force that style of working to others, I feel it's working great for me - it leads to well thought out coding, and can _never_ lead to undocumented code.
However others work - what you describe and recommend here is nothing else to me but the title of this website...

Henning on July 25, 2008 4:29 AM

The solution, of course, is to use the "Commentator":
http://www.cenqua.com/commentator/

tragomaskhalos on July 25, 2008 4:31 AM

Oops, wrong URL - get me here: http://lazyb0y.blogspot.com

Henning on July 25, 2008 4:32 AM

I suppose the level of detail in comments depends on the level of understanding by the people looking at the code; where I work, not all 'programmer' are at the same level (I wouldn't even consider some of them programmers at all) so whenever I loop through an array I have to write down what's happening otherwise I get people ringin me up asking me what's going on.

silence on July 25, 2008 4:44 AM

Jeff,

I couldn't agree with you more. In fact, I wrote a very similar post 7 days ago about the exact same thing (shameless plug: http://tinyurl.com/6m8tsl). I think my language was a bit stronger against comments, but your language was clearly more articulate.

Brian Genisio on July 25, 2008 5:01 AM

Jeff,

>Do I really need to write a post saying "comments are good, please use them?" That's like writing "code is good, please write it."

No. Make people reflect. Let them benefit from your experience. Show them the "how", not the "what", and let them draw the conclusions on their own. Put things into perspective, rather than advocating one side. You've got an audience, so you've got responsibility.

>If the best code is no code, what is the best comment?

Well, if the best code is no code, then the best job is no job. Ex falso quodlibet ;-)

Sure, I agree that less is (sometimes) more. But you also know that there's a limit to "quality by reduction". Why shouldn't the same be true for comments?

Leo on July 25, 2008 5:06 AM

you are a shameless flame-baiter

structure on July 25, 2008 5:14 AM

Another excellent compromise that you skipped, is meaningful variable names! I am not familiar with Newton's Method (might have seen it in school, *coughcough* years ago), but it looks like r is the root and t is a tolerance. Why not call them that? "while ( abs( root - (n/root) ) > tolerance )" would have been clear enough that I could figure out at a glance what that was trying to achieve.

Dave Aronson on July 25, 2008 5:16 AM

Harrumph. I *did* check to see if anyone had already commented on the var names, but for some reason the web site only showed me the comments written up to Dan's of 08:09 PM last night. Methinks there's a naughty cacher somewhere on my slow link. Sorry! B-(

Dave Aronson on July 25, 2008 5:20 AM

Jeff:

Comments are for the next guy who has to modify the code at 3 am when production is down and the original programmer has moved on. As a maintenance programmer for several decades, I can tell you that novel like comments do not help. But single letter variables that you used in your example do not help either. You are making the assumption that the next guy in line will know what you know the instant you are writing that line of code. (That next guy could be you 6 months later and at 3am all math is fuzzy logic.) There are coders and there are programmers. Programmers don't ASS-U-ME!!!

private double SquareRootApproximation(square) {
rootApproximation = square / 2;
while ( abs( rootApproximation - (square / rootApproximation) ) > tolerance ) {
rootApproximation = 0.5 * ( rootApproximation + (square / rootApproximation) );
}
return rootApproximation;
}
System.out.println( "r = " + SquareRootApproximation(r) );

Will on July 25, 2008 5:28 AM

Jeff, I have lost the last little bit of respect I had for you with this post. :P

Seriously, though, I do find short "what are we trying to accomplish here" header comments helpful. Note that your refactored example no longer conveys the fact that it's doing a Newton-Raphson approximation. Maybe that's not a big deal there, but there are other situations where a fact like that would be good to know.

I like the goal of code blocks to be commented, so "what" in the sense of "what are we trying to accomplish" instead of "what are we doing" (which you correctly say should usually be understandable from the code itself).

Bob on July 25, 2008 5:31 AM

Reminds me of one of our junior developers here. Her manager told her to comment a lot, so she does things like:

//Get the http session.
HttpSession session = request.getSession();

Which is utterly useless and just clutters the source files.

a on July 25, 2008 5:34 AM

@Will:

You just beat me to it.

Good method naming is great for people calling your code. For people actually maintaining your code, all naming is important. Method, variable, class, etc names should all be descriptive.

If there isn't a clear name for an entity, there's a very good chance that it shouldn't exist in the first place.

One good example is loop counters. How many times have you seen "for(int i = 0; i < some_number; i++)", when there is actually a meaning to the loop counter, such as an array index, or something_count?

By all means, keep code terse, but not to the point of obfuscation. FFS, a couple bytes of extra code for clarity is great value.

Chris on July 25, 2008 5:41 AM

try writing some readable assembler code without comments... good luck with that. :)

good post. i am often guilty of explaining in too much detail how something works in comments, whilst leaving other things uncommented altogether when they really need a good comment...

jheriko on July 25, 2008 5:46 AM

I still put some comments in my code, but I do make my code descriptive. The comments are typically for me, as more of a reminder of what I was wanting to do when I start to stud out a new class or method. I'm starting to do that with the TODO comments, but learning how to code w/out having that option available, I just got in the habit of one line comments as a quick reminder to myself of what else I needed to to do.

mjmcinto on July 25, 2008 5:52 AM

I agree with Will. I have personally been in the situation where I was asked to add a feature to a program that I had written three years earlier. I *thought* I had a good idea in my head as to how the original source code ran, and foolishly answered that it would be easy. I had a pretty good idea how to do it. But then when I looked at the actual code (with no comments, and with variables named 'x' and 'y' etc.) it took much longer than I had predicted just to find the right place to modify the code. FWIW, once I figured out *where* to modify the code, the actual modification was as easy as I thought. If only I hadn't used up more than my allotted time for making the modification just figuring out my own code. BTW, this wasn't even at 3 AM.

Pete S on July 25, 2008 5:53 AM

I have worked on teams where EVERY new line you write needs to have a comment (and the version control nazi/supervisor would nag you to death if you didn't). That certainly doesn't help anyone. If I write a function called "ClientAuthNumber(client_id)" I don't think I should need to add "// returns client authorization number based on client id" or "a = b + c; // a equals the sum of b & c" ...but I guess there are those who disagree.

On the other hand (and just as important), my team is now working on a huge application written by another company which we have to manage and there is hardly a line of code on anything. It seems for about a 2 year period from 2005-2007, they usually added just who updated it and when...not why it was added or if it affects anything else.

IMO, there is nothing harder to read than code that has 2 lines of comments before every line of code. If it is that hard to understand without EXCESS commenting, maybe it wasn't well-written to begin with...

bob on July 25, 2008 5:59 AM

Wow, Jeff is really on a roll here. Code and comments are bad!

I guess I never realized that Coding Horror was actually about coding badly. Comments are not bad, *BAD* comments are bad. Just like code isn't bad, but bad code is bad.

I'm honestly having a hard time believing someone as supposedly intelligent as Jeff actually believes this crap. It looks to me as though Jeff has discovered if you post controversial stuff you'll get more ad hits. Whatever, thats his prerogative but I'm not reading it anymore.

Matt Newman on July 25, 2008 6:08 AM

Comments are my friend. Sure I could write a big block of code and walk through it to see what is done, but isn't it quicker to just read a sentence or two before it so that I know what it does?

In addition, if you code something wrong (not that I would do that, but maybe some other developer would), wouldn't it be nice to have a comment that says what the code SHOULD do?

My favorite comment is when someone does this...
x = 2 // set variable x to 2.

Not that I'd ever use that, but it makes me laugh when I see it. And then die a little inside.

Kris on July 25, 2008 6:09 AM

I totally agree with the article.

Luigi R. Viggiano on July 25, 2008 6:16 AM

As I think one or two others may have pointed out (rather verbosely, haha), I also use comments fairly often to document design decisions.

My present example is a checkpoint system for realtime data, the logistics of which make my head spin. So there are little hints peppered around the provider class that explain, for example, why the end date of some checkpoint is not the same as the end date of its corresponding transaction. Or why the "original" and "modified" parameters are swapped in a certain call (I can just imagine someone reading the code, assuming that was a mistake, and proceeding to break one of the most critical components).

Of course, most of my smaller projects have no comments at all - they're simply not complex enough to require them. There aren't really any significant "design" decisions.

Actually, Jeff, in this case, I think both the original example and your "refactored" version are wrong. There should be a comment, but not the comment that's there. The comment should answer the question: why are we using a hand-rolled square-root-approximation function when there's already a perfectly good sqrt function in the math library?

Aaron G on July 25, 2008 6:24 AM

Alex: I think you're correct for the first time through the loop, but after that it changes and converges on the result.

mike on July 25, 2008 6:32 AM

One of the most important things I use comments for is to explain what is not available from looking at the code. For example a requirement of a called procedure:

if (x < 0) then AbortProgram("X is negative");
y := PerformSomeMagic(x);

May deserve the comment:

//PerformSomeMagic will give incorrect results if passed a negative parameter.

Al on July 25, 2008 6:38 AM

I think Jeff has made his point by using an over-the-top comment example. I also comment methods before writing them. But I'm a bit more succinct about it (VERA code in a HW verification test bench):

// After (possibly a series of) call(s) to
// set_field, this task is called to write
// the shadow_value to the physical DUT CSR.
virtual task commit_fields_t(integer access_method = CSR_DEFAULT_ACCESS);

In my last post, http://mjbiren.blogspot.com/2008/07/check-in-your-changes.html, I note that one of the things you need to do when checking in changes is to make sure the comments are still relevant. This becomes easier if the comment's content is short and only about code intent. Code details always change, if you comment like you're writing code - then changes always become twice as much work.

So in the end, I think I half agree with Jeff.


mike on July 25, 2008 6:42 AM

No use of regions in you code, no comments, what's next? Shall we say no to line breaks. Visual Basic you need them, but C#? It's just a waste of space not to be using every pixel of your screen for conveying information. Why should I have to use my mouse wheel to scroll up and down someone else's code when they could have fitted it into one small area. This would allow me to have many classes open on my screen without having to alt-tab between them. So efficient is this way of code that before reading any code I run a script to remove all white space from it and check it back in. Another advantage to this style of coding; I can use a USB photo frame for displaying some of favorite classes of code. Code Analysis can now include looking for secret "Da Vinci Code" messages. The fate of the world is in your hands if only you would advocate proper coding standards. Come on Scott the world needs just one more controversial coding practice to save it.

Dave on July 25, 2008 6:45 AM

In a perfect world our comments would write the code.

Practicality on July 25, 2008 6:45 AM

And then your subroutine fails because t is undefined.

dnm on July 25, 2008 6:55 AM

I dunno, I would still appreciate a one-liner about which approximation algorithm was being used. Numerical methods isn't my strong point.

(@Will: The use of short variable names in the refactored function is fine; it's a math algorithm and you need to be familiar with the algorithm to get it anyway; the long variable names doesn't help there.)

Adam Vandenberg on July 25, 2008 7:02 AM

How to dupe the world into thinking you are an Authority: Write lots of opinionated, loud blog posts on lots of subjects. It's fast becoming clear that Jeff Atwood is not a skilled developer. In fact, as you watch his writing about stack overflow, it becomes very clear that he is flying by the seat of his pants and has no idea what he is doing. He even admits that he has some sort of pathological need for public attention in the last podcast. Sure, it's entertaining, in a train wreck sort of way, but I sure feel sorry for people who come here thinking they are getting good advice and that Atwood knows what he is talking about.

Jon on July 25, 2008 7:02 AM

In our organization (or the part I'm in, anyway), good practices like commenting code have not been paramount. I'm working to change that, including a requirement in the group I lead that we comment our code. It doesn't (and shouldn't) be book length, but some helpful hints here and there, telling "the next guy" what was intended, is very helpful.

Scott Marlowe on July 25, 2008 7:02 AM

Comments are an invaluable tool designed to communicate what is otherwise incomprehensible. If I come behind you, I'll be cranky because I have no idea what the "Newton-Raphson approximation", and you didn't bother to make a comment on the subject.

Sometimes we have to write highly complex code, and comments are a way to help understand those tough blocks, but the real power of comments and where they shine is communicating business concepts. After all, it's our job to help the business move forward, so that is where we have to focus our understanding.

Just my two cents.

Corey Furman on July 25, 2008 7:05 AM

I had a college professor who loved to kill us with documentation - his favorite example was "How zero's do you see? 000000000" and then he showed us "000|000|000"

The professor said: "See - I added more stuff and it's more readable!"

Years later - I realized you could use whitespace and change it this to get the same result: 000 000 000

Sometimes less is more.


john on July 25, 2008 7:11 AM

Yep, must agree with the majority of posters here and disagree with Jeff. I start with comments as I set the architecture in place and then flesh it out with code. Yes, the comments typically stay in some form. And if you wanted your function (which I wouldn't make something a function just to avoid a comment block), then it would require more work (which I would argue it needed anyway)...

// Newton-Raphson approximation
private double SquareRootApproximation(iRoot) {
fRootApproximation = iRoot / 2;
while (abs(fRootApproximation - (iRoot / fRootApproximation )) > iTolerance) {
fRootApproximation = 0.5 * (fRootApproximation + (iRoot/ fRootApproximation));
}
return fRootApproximation;
}

System.out.println( "Root Approximation = " + SquareRootApproximation(iRoot) );

Phil on July 25, 2008 7:13 AM

I would have to agree that self-commenting variable names and function names area always more valuable.

As far as the other comments, my commenting style is constantly changing. Sometimes more, sometimes less. I nearly always think what I am currently doing is the best. I am sorry to say, but I think there are pluses and minuses to both. Assets and liabilities.

It's actually just a preference. Seriously (as long as your code is actually easy to read).

Practicality on July 25, 2008 7:22 AM

In Russia, comments write *you*.

B0R1S on July 25, 2008 7:26 AM

Most of my work is cleaning up and maintaining existing code. Usually the original developer was a newbie, the code is hard to read and comments would make my life a lot easier. However, if the code was written by someone who knew what they were doing it's usually obvious what is going on and comments are already in places where it makes sense to have a comment. I think the longer a developer codes, the more he/she learns to write "self-documenting" code and when/where to add a comment.

PaulG. on July 25, 2008 7:30 AM

> Junior developers rely on comments to tell the story when they should be relying on the code to tell the story.

I disagree. Comments are the context which code itself might not provide. Normal human reasoning does not always align with code architecture; this is why we consider a meaningful understanding of design patterns to be one sign of maturity (i.e., they take effort to internalize). Just as a graphical interface needs both a usable design and helpful documentation, so does code. This is because none of us are savant designers, capable of providing fully-comprehensible designs (to all audiences, locales, and experience levels!).

That's my "big picture" response.

On the pragmatic side, engineers in any rapidly-changing field will need to frequently migrate between languages, platforms, and goals. While we should all have a firm grasp of programming fundamentals, the reality is that we often need to modify code we're not seasoned veterans of.

If you have the luxury (or curse?) to work in one language for your entire career, then comments may seem superfluous. But throw in either a complex architectural solution (e.g., for performance or enterprise integration purposes), or new languages and libraries, and all-of-a-sudden a few comments here and there significantly improve task completion times.

Everyone benefits from comments -- junior and senior engineers alike.

Vance Vagell on July 25, 2008 7:37 AM

"You should always write your code as if comments didn't exist."

I agree to the fullest, although I find it hilarious that you can say this in the midst of using single-letter variable names.

Josh Stodola on July 25, 2008 7:40 AM

// Constant Comment is a pretty good tea.

Charles on July 25, 2008 7:44 AM

Just... whatever you do... don't add regions!!!

/had to

Ivan on July 25, 2008 7:44 AM

The best comments are like:

// Increment i
i++;

George on July 25, 2008 7:50 AM

"While comments are neither inherently good or bad, they are frequently used as a crutch. You should always write your code as if comments didn't exist. This forces you to write your code in the simplest, plainest, most self-documenting way you can humanly come up with."

Disagree. Comments exist for a reason, we should make use of them, not write code that doesn't need comments. Its not like comments are included in the compiled code. Shit most editors, make comments a different colour, you can easily ignore them. You know your blogs bug me. You moan about everything, php, xml are ones that stick out in my memory. Maybe you are an old school programmer who doesn't like the new breed. But i'm afraid we are in a field where what's new is old before it hits the mainstream. You need to adapt man!

Back to your comments hissyfit, I try to write efficient code ie use less memory, less cpu time etc... This some times leads to the code being hard to understand, no matter who is looking at it. Yea i try to keep it simple and plain, but sometimes to get that speed plain and simple doesn't work. So comments come in, not on every line, hell no, but a little summary saying what the method does is quite fine.

Mitch on July 25, 2008 7:50 AM

As stated above by several others, my most common use of comments is for business logic. As the majority of applications I work on are complex applications with obscure business rules, leaving comments definitely helps future developers on the project.

David Parker on July 25, 2008 7:54 AM

The argument that

SquareRootApproximation(n, Type.NewtonRaphson)

is more readable than

// Uses Newton Raphson
private double SquareRootApproximation(n)

is pretty weak. I'd rather see a comment here than the first one. While I think you do have a good point about bad comments, please try to find a better example before you make your point. The current example is terrible because it does need at least one comment to be completely readable and easy to maintain and therefore, weakens your point considerably.

Cecil on July 25, 2008 7:56 AM

At school, the only thing the profs teach in the first 8 weeks is commenting. In my first year the teacher would knock points off every program we wrote, if there wasn't at least one comment for every line of code.

Chaise on July 25, 2008 7:56 AM

I like comments as easter eggs -- my last day at a job I added a joke to a colleague as a comment. Three months later I got a nice call from him :)

paul on July 25, 2008 7:59 AM


Scott please bring some perspective to you blog entries, you make some valid points but why do you see the need to make everything so extreme?

I promise to carry on reading but I would prefer a more balanced discussion. I appreciate this is YOUR blog, but as you have clearly positioned yourself as a semiprofessional blogger, I'm not sure it is becoming of you to be so myopic.

Joe on July 25, 2008 8:04 AM

I think the one point developers should take out of this is the bolded note "You should always write your code as if comments didn't exist." It's probably one of the hardest tasks in our world and for those of you against self-describing, simple code, shame on you. There is enough complexity in the systems we produce that it makes little sense to have it at the functional level.

I am often guilty of poorly name variables (love the 1-, 2-, and 3-letter names...) but I often find myself going back and renaming them later. My past excuses for short names has since been trumped by Intellisense -- less time is compromised by "typing" long names as the IDE does it for me now.

I've had one "what-the-heck" moment with some critiqued code. The first was with a continue statement in C++. "You should put a comment in there to say what 'continue' does." My confused reply -- "You want me to explain a keyword of the language?"

The last comment as I'm typing this is "In a perfect world our comments would write the code." I like the implications of it -- imagine a world where people used proper grammar and spelled words correctly...

Great article Jeff!

Austin on July 25, 2008 8:06 AM

Some sniglets for you:

Obso-doc: Comment detailing what the code did last year.

Redundo-doc: Comment literally describing source code statement(s).

Histo-doc: Ever-increasing comment section detailing revision history, typically duplicating information in Revision Control.

Igno-doc: Comment revealing author's lack-of-understanding of necessary algorithms, alternate syntax, etc.

Personally, I believe in minimal commenting in-code (doesn't count "Javadoc" documentation, which I don't consider comments) only to warn subsequent visitors (like me during maintenance) about certain code sections that are arranged a certain "atypical" way on purpose, i.e. to workaround something somewhere else. I prefix these with "IST" for Important Safety Tip! This heads off the "What the F*** was he doing here?" impulse to just rip it out and re-do it the "right" way.

The Gassy One on July 25, 2008 8:28 AM

My extended thoughts on this (in addition to comments posted above):

http://www.krissteele.net/blogdetails.aspx?id=70

Kris on July 25, 2008 8:33 AM

Not a fan of literate programming then?

http://www.literateprogramming.com

Personally, I think Knuth is on to something very valuable.

Like you, I really appreciate self-documenting code, but there are times when comments are absolutely essential for the next developer.

Your post can too easily be misconstrued; and, if there is one extreme that I have come across all too often it is the absence of comments.

Jeff, have you ever worked as a maintenance developer on a large application?

Jo on July 25, 2008 8:37 AM

I prefer to start with comments and fill in the code. This leads to good comments and good code. Once the code is working, I might prune/edit the comments that are redundant.

Giant template-driven comment blocks at the tops of files and before each function are useless.

One of my pet peeves is when people comment the interfaces with implementation details, and the implementation details with instructions for use. If you're in C++, where prototypes are often separated from implementations, it's good to think about the appropriate comments for each context. People looking at the prototypes are trying to figure out what your function does and how to use it. Developers looking into your implementation need to understand how it works and why you made certain decisions.

The commentless Newton-Raphson example could still be improved with a comment that says "Newton-Raphson". At least that's something someone unfamiliar with the algorithm can search on.

Adrian on July 25, 2008 8:39 AM

Good timing. I was just hired to add a video snippet of code into someone else's website. The previous developer most have thought it was cool to reformat all of the code into one single line with no spaces or comments. It's a mix of bad ASP and HTML. So now I believe the previous guy knew he sucked and just wanted the code to be difficult to edit by the business owner.

So the ethics question is should I just insert my properly coded, commented, indented and extra white lines of code into the other guy's jumble of mess? Or should I spend the extra time on the previous developer's code and force line breaks at all of the right spots, create indentions at all of the right nestings and add comments as to what I think he meant to do???

Well this client happens to be my friend on my weekend soccer team and I think I'll extend the courtesy to clean the entire page.

My take on comments...

I give my clients the "If I die" speech each time I run a project where they are given complete access to all source code, source images and help files for easy transferance to any other programmer. And within the source code there is just enough comments to help a decent programmer. And within the source images, there are just enough comments on each layer to help a decent designer. When I mean decent, I mean that the comments are not too long or descriptive to help a non-programming business owner think that they themselves could attempt to make code changes. (dangerous).

Paullee on July 25, 2008 8:46 AM

I always heavily comment my code. It's not just for people to follow behind me. No. Its because 2 weeks later I'm knee-deep into something totally different and when I return to the previous code I need a gentle reminder.

As far as not having comments in your code, couldn't you use a comment stripper as part of your automated build process?

Ian Patrick Hughes on July 25, 2008 9:01 AM

Here is another one:

Identi-doc: Author tediously annotates each modification with their date/initials.

I don't know how many times I've seen this! Please everyone give that one up.

The Gassy One on July 25, 2008 9:01 AM

Heh, aren't function names themselves an abstraction designed to succinctly describe a block of code to programmers, just like comments? I mean, computers don't really care if you call it "SquareRootApproximation", "foo" or 0x00401000.

Saying comments are bad is like saying coding is bad. There are intelligent and stupid ways of doing everything.

Also, C#'s /// syntax is arguably superior if you want to add descriptions to the autocompleter or to API docs. You can't make function names link to a Wiki article on Square Root Approximation. Why settle for that, when you can have an actual description in plain english and rich text markup support?

Leo Horie on July 25, 2008 9:03 AM

The first thing I do is write a comment block. Where I work, it is very unusual to be given a specification on what has to be done. (Most management types are mechanical engineers.) I then use the comment block as my coding specification and I code to it. Then, sometimes, I update the coding block to match the code.

Eric Hamilton on July 25, 2008 9:05 AM

Please, pass the approximation threshold (t) to the private method.

Daniel on July 25, 2008 9:07 AM

I think ApproximateSquareRootOf( n ) would be even better. I always tell my developers that code shouldn't need comments. Methods should be small and well named, the best ones should read like English inc which case the code becomes the comments. Complex methods almost never exist. They are instead simple method comprised of still smaller and simpler methods.

Conditional clauses are my favorite. They almost never tell you the intent:

if( lstItems > 0 && lstItems != null ){}

gives me a lot of technical details.

if( this.AccountIsSelected() ){}

private bool AccountIsSelected()
{ return lstItems > 0 && lstItems != null;

gives me so much more information. And hiding that clause in a method lets me abstract away those details if I'm a maintenance program so that I don't need to keep everything in my head. Is the program having a problem with the account a user is selecting. No? then don't trace into that method...

Russ McClelland on July 25, 2008 9:14 AM

There is a fatal flaw with your example. When you named the method "SquarerootApproximation" the information about *which* approximation you are using is
If you made a mistake or there is some problem with that approach then you've just lost some vital information! Oh course "NewtonSquareRootApproximation" is not appropriate since that's an implementation detail.

The point of the article should be what information should be expressed in comments and what should be expressed through refactoring, method names, and variables. It seems to me that there is NEVER a method that needs *no comments*. After all what does your method do when the number is negative? There should always be _some_ comments, but always try to see how much of it you could express in other ways.

That's my $0.02.

Art Bugorski on July 25, 2008 9:36 AM

I think the Spartan Programming (http://www.codinghorror.com/blog/archives/001148.html) approach also applies to comments. For C#, I use the XML documentation comments and then I decompile my assemblies using Reflector. If the code and documentation that show up in Reflector aren't understandable, I refactor my code and revise my documentation until I can't make it any better. Then, if there's still something that isn't clear, I comment it.

Matthew Kane on July 25, 2008 9:41 AM

Totally in agreement. I take comments in general as an indication that the code itself has not reached its perfect state of self-evidence.
I attended a panel with the authors of "Beautiful Code" not long ago, and one of the authors mentioned that in his opinion, the only valuable comment in code was "do not change this!"...

Mathias on July 25, 2008 9:44 AM

I agree with Jeff ... up to a point. If you can document the code using the code itself, then you absolutely should, and comments that simply reiterate what the code says are an abomination and should carry the death penalty.

Having said that, in my actual programming work I tend to use comments as commentary ... at intervals, come up for air and jot down a note on where you've got to and what the state of the system is. I would say "the code describes what the program is doing, the comments describe what the programmer is doing" if I didn't suspect it of being a nice but meaningless sound bite. Comments don't appear every line, but generally before a compound statement, if/switch, function call or group thereof.

The last comment I wrote, incidentally, was "A push of CS in 16-bit code is taken to imply a near call to a far function. Provided the next instruction is in fact a near call, we can just ignore it." I don't think you'll make the code that does that look like the comment that describes it.

I am, occasionally, guilty of the silly:

// What do you call a function written by a chav?
void init(void)
...

jim on July 25, 2008 9:45 AM

"if your feel your code" should be "if you feel your code".

Excellent post. Thanks!

Raam Dev on July 25, 2008 9:48 AM

While I agree that meaningful method names are a big step in the right direction, meaningful variable names are just as important. In your example I have no idea what n, r, or t mean, or why you're performing those operations.

Jesse on July 25, 2008 9:52 AM

As Jeff points out, comments are ok, but the need to tell us WHY something works. WHY did we do it this way? WHY did we take the sub-optimal path. WHY shouldn't I change this code at a later date?

Take this example from real-world code:

byte[] docBytesHash = MD5.Create().ComputeHash(docBytes);
StringBuilder sb = new StringBuilder(32);
for (int i = 0; i < docBytesHash.Length; i++)
sb.Append(docBytesHash[i].ToString("x2"));

What is does is somewhat obvious, and may net even need a comment. But how 'bout this:

//remote machine seems to use case-sensative comparison
// don't change below to be "X2".
byte[] docBytesHash = MD5.Create().ComputeHash(docBytes);
StringBuilder sb = new StringBuilder(32);
for (int i = 0; i < docBytesHash.Length; i++)
sb.Append(docBytesHash[i].ToString("x2"));

That comment tells me somthing that no code could tell me. It tells me about a dependency on a remote piece of code and a reason WHY something is coded that way.

WaldenL on July 25, 2008 10:01 AM

"I haven't added a single comment, and yet this mysterious bit of code is now perfectly understandable."

The fact that this is bs, because the approximation algorithm is non-trivial, has been well covered.

But I would also add that the new code is also missing any sort of explanation for why you would use this thing. Of course, I suppose Jeff could add that to the signature as well

r = calculateApproximateSquareRootBecauseCallingSqrtDirectlyReformatsTheHardDrive(n)

Danil on July 25, 2008 10:10 AM

Jeff, please learn the difference between documenting the (intended) interface, and "code comments": documenting some possibly weird lines of code.

After that, you may come back to talk about "code with no comments" and I'll be happy to read your blog again.

Your first pseudo-example for "excess comments" proves my point: Two lines of the comment are actually "interface documentation", the rest is either implementation detail (which could be easily extracted from any actual code here, I hope), information which you could get more reliably from your source control system, and totally irrelevant stuff which you just made up, probably because without it it didn't look worse enough to prove your point.

Although, I must admit I didn't quite get your point yet - maybe we need to add more comments. ;)

Vinzent Hoefler on July 25, 2008 10:17 AM

Good article, I often will use comments as little notes to myself as I go. They usually melt away once I refactor the code pending passing tests.

ps. Those scoping braces on the same line as your statements are cringe inducing. Blech.

J.S. on July 25, 2008 10:35 AM

The first time I had a copy of Code Complete in my hands, somebody had told me "You can really just open it to a random page, and there will be wisdom there. It's uncanny". So I tried it. I picked a random spot in the book, and opened to a section that discussed commenting code. What it said was something very similar to your argument. Paraphrased from memory, "Comment to your code. Then rewrite the code so it doesn't need those comments. Then comment that."

Alex on July 25, 2008 10:43 AM

I would like to see a similar post about logging. Fellow programmers use logs as debugging tool... They keep the same debugging comments as operational logging comments when in reality they don't mean much to the people operating the system.

Joes on July 25, 2008 10:44 AM

I, for once, tend to agree with Jeff.

You can certainly take it too far, but given a choice between descriptive subroutine/variable names and comments, I'd pick the descriptive names.

Paul Houle on July 25, 2008 10:58 AM

re senior v junior programmers.

You're way off. I find the juniors are the ones who blat out code without putting comments in, these are the ones who tend to think they know what they're doing and commenting would just slow them down.

Senior devs tend to comment what they intend the code to do as they go along.

On the other hand, perhaps junior = poor, and senior = good would be better descriptions.

AndyB on July 25, 2008 11:05 AM

Nice post! Even as I myself am a Technical Writer, zillions of comments in code don't make documentation necessarily better. It is QUALITY of comments, in my opinion, that are what really make a positive impact on the generated documentation.

Keith Johnson on July 25, 2008 11:22 AM

Am I the only one who dislikes refactoring to the point where each function has a huge name and only a line or two of code? I also have to agree with the other poster who doesn't like huge variable names. I think there's lots of cases, especially in numerics and scientific coding where complex algorithms can't be easily refactored into one-liners and well-placed comments are needed to make the algorithms comprehensible.

Totally agree that the old-school documentation blocks as shown at the top of your post are horrible, though.

queisser on July 25, 2008 11:30 AM

Jeff, what the hell is 'r' ? ;) Shouldn't it be 'root', or even 'squareRoot'?

And 't' isn't even defined here, but it needs a better name too.

I agree with the other commenters who suggest that you should still have a comment identifying that you are using the Newton-Raphson technique. Makes it easier for a maintenance programmer to identify the algorithm and look up its pros and cons.

Dan on July 25, 2008 11:30 AM

How bad is the code which checks for "orange"? Must have some values stored in Octal.

BugFree on July 25, 2008 11:34 AM

Because you work with joel, you think you can give us the advice of the day (Don't disable menu item) ? I mean, programming and one of your favourite book is all about subtility and heuristic, and not giving some "rule" you illustrate with a two line function.

This is blog trollism. Hopefully the link are there to provide us some content, and steve yegge's post is great as usual. You have a great blog, but please, give it up a bit with your "strong opinion, weakly held" motto.

I hope you don't do spartan programming + no comment, the result must be quite ugly :)

bandini on July 25, 2008 11:50 AM

I ran across some old Basic code the other day that I understood absolutely perfectly. I understood everything that it was doing.

But I had no idea WHY anyone would do this or WHEN it happened or WHAT it was trying to accomplish in the big scheme of things. It was clear...but pointless.

It took me 1-2 hours to figure out the code but 2 weeks to figure out when it was used and why.

Even Jeff's comment about SquareRootApproximation misses the point. As long as you tell me it's a square root function (comment or method, don't really care), I can test it fairly easily and I care very little which method is being used because I can easily replace (with "return Math.Sqrt(n);") it if it's found to be wrong.

But why the HECK is Jeff rewriting Square Root anyway? Does Math.Sqrt() have a bug or something? Does one of the many easier alternatives of computing square roots not work?

I still have absolutely no idea why this was done, what to do if it has a bug in it, nothing... Everything Jeff made a huge deal about in the article is rather pointless when I come back to his code.

Huge comment block? Easily ignored with PgDn.

Comment or Method? Don't care.

Using an enum parameter to avoid a comment? You're an annoying dork, but I don't care.

Not giving the how, why and when? Major issues when it breaks.

PRMan on July 25, 2008 11:51 AM

I'll agree with Jeff on this one. Write the code to be as clear as possible. Use peer review to help. Comment on WHY and not WHAT.

I've worn out many a Page Down key by skipping over headers in files (my last company required them). Most of the time the WHAT didn't match with the working code, so I acquired the habit of not reading them.

For those of you who have never seen too many comments, consider yourself lucky. I had one project where the developer put no comments in 30,000 lines of code. He was told to comment the code, so he wrote and AWK script to put comments on every line. The comment was usually one word, such as 'yes' for if (someCondition) and 'no' for else {}, and 'oops' for exception handlers. The code itself was pretty good for it's time (1994), and when I asked an old co-worker about it, is still in use today.

Tim on July 25, 2008 12:03 PM

>private double SquareRootApproximation(n)

Great, now you're paying function call overhead on each call for an algorithm that is usually used in places where it needs to be run often and fast. The comment would have been a much better choice.

>Comments rapidly become out of date with refactoring, and with fellow programmers not updating it.
That is an excuse for sloppy and lazy programmers. If it hurts when we that, then maybe it's time we figure out that we shouldn't be doing that. I suggest a simple four step program:

First offense = verbal warning
Second offense = noted on performance review
Third offense = forfeit bonus
Fourth offense = termination

Harsh, you say? Far mor lenient than government or financial institutions' penalties for not keeping your house in order, I say.

>Also, why are you reading the code if you don't know why or how you got there?
I take it you work in a rather sheltered environment. Ever have an emergency fix request for a project you never worked on dropped in your lap?

>If you can't tell what the code does without comments, the code isn't done yet.
Have you ever considered the fact that the maintenance programmer is likely not going to be at the same level of experience and skill as you and is going to need some crutches?

GrumpyYoungMan on July 25, 2008 12:05 PM

Commenting code goes way beyond typing double slashes and telling little stories.

Jeff has demonstrated some great idea's that go beyond what a beginner would.

Isolating a code fragment (probably re-usable at that) and giving it a meaningful name is a great first step.

Getting all of the FM (Funny Magic) numbers out is great too. Constants can be named to something meaningful to add context. I realize that the constants in this example are too simple to bother naming.


I am undecided about where to document the actual Newton-Raphson algorithm and will sit on the fence on this one.

Putting a type declaration on the argument list on the method call certainly alerts callers as to what algorithm is being used, but I still wonder if that should be encapsulated inside of the function itself.

Hard to answer without knowing the importance of the algorithm and why it was chosen instead of a standard library function.

davide on July 25, 2008 12:09 PM

Agree, i have no problem with naming stuff like GetWeekNumberStartingFromLastMondayOfPreviousYear(), with intellisense you only have to type 3-4 letters anyway.

But if you have to concat some strings with several calls to the method i try to come up with a shorter name.

Crazy Ivan on July 25, 2008 12:10 PM

-- 8< -- snip --
I had one project where the developer put no comments in 30,000 lines of code. [...], and when I asked an old co-worker about it, is still in use today.
-- 8< -- snip --

That's probably because no one dares to touch 30K lines of code without having a clue what it is supposed to do.

SCNR.

Vinzent Hoefler on July 25, 2008 12:15 PM

When it comes to comments I find I have a "weak beliefs, weakly held" methodology. Verbosity, lack thereof, algorithm references (eg "Newton-Raphson"), "why vs how"- I mean, any one of reasonable programming experience could argue any one of these, on either side, indefinitely. The only advice on commenting I ever hard that I really feel should be applied in all situations, is in the beginning of every oreilly book. "If any of the previous rules makes the code less readable, throw [that rule] out."

Every rule you ever hear about good commenting is a guideline. There will be exceptions to that guideline. Pointing out exceptions to the guideline as proof that it's not infallible (and implying that not infallible => bad guideline) is honestly kind of useless.

Alex on July 25, 2008 12:19 PM

I agree that comments need to add value to the code and need to be maintained; however, I disagree with over-reduction of comments.

Source code is designed to bridge the gap between machine logic and human communication/thought. While this makes it a great medium for telling the machine what to do, it's not designed to be as fluent or natural as human language is. Reading code requires a mental translation to occur before you can make sense of it. Writing code requires that same process in reverse.

I comment a lot (oftentimes, every line.) I do this because if I can't write out the code in English, I don't understand enough of what I'm doing to be coding it. When I later revisit the code, I can read it in my own words just by reading through the comments. I also use such comments to refactor and clean up what's going on. It's easier to spot logical errors when you can see them in your own words.

I'm sure there's a benefit to developing a mental process that handles this translation for you but to me it seems unnecessary. I want to focus on the "essence" of the code not the semantics.

Nicx on July 25, 2008 12:39 PM

I've heard this before, and I consider it disingenuous. Only a relative few are able to read code as effectively as a code interpreter. I've worked with many developers over the last 20 years and I can't think of a single individual who could do it perfectly.

What does this post really mean? Should everyone unable to read code as efficiently as the author go dig ditches for a living? The vast majority of coding is done by "average" developers who may need comments to help them along the way to comprehension.

This is especially true of maintenance development where coders are reading code which may be many years old and have numerous coding styles, with little or no documentation to follow as to the purpose of every function or feature.

Nick Waters on July 25, 2008 1:51 PM

It's funny how often I see people complaining about out of date comments then not fixing them.

Most of the "comments make the code less readable" argument is simply looking for an excuse not to have to explain what their own crappy code does when they often don't understand it themselves.

Personally I have really wanted comments quite a few times just to judge the intelligence and intentions of the author. Did he know what he was doing when he added this apparently extraneous variable? Often you don't find out that it was actually a key hack added at the end to support some business rule until you're in the middle of removing it.

Any time you hit code that you don't get within a few seconds, be it yours or someone elses, FIX IT. Either add comments (which has the benefit of virtually never breaking the code) or refactor the hell out of it until you have something understandable.

If you just leave it and work around it, letting the next guy start from scratch as well, you're worse than the original author because you KNEW there was an issue.

Basically your code should read like a book when you are revisiting it (not when you are writing it and it's fresh on your mind). There should never be a question as to why you are doing something.

As you pointed out, this can often be done by very small single purpose methods and classes that are appropriately named (Anyone that thinks that simply naming things well will do it is part of the problem though).

Honestly it's a LOT more work to make readable code than to write a few readable comments, and I doubt a lot of programmers are even capable of writing readable code--then someone comes along and gives them the idea that using a 30 character method name for a 200 line method is going to absolve them of all responsibility.

Bill on July 25, 2008 2:11 PM

While I absolutely agree about properly factored code and good naming conventions, I think this conclusion is naive:

> if your feel your code is too complex to understand without
> comments, your code is probably just bad. Rewrite it until it
> doesn't need comments any more. If, at the end of that effort, you
> still feel comments are necessary, then by all means, add comments.
> Carefully.

It only works in simple systems where you, the singular developer, control the entire codebase, any you're not interacting with any other systems. For instance, it works great for pure data-in/data-out algorithms.

Reasons for commenting usually have little to do with the quality of the code itself, but rather a limitation of the architecture you're living in - for instance, the web.

When your application is spread across server and client code, UI code/resource bundles, CSS, etc, and depends on the quirks of HTTP caching, SQL performance characteristics, third party libraries, etc, you absolutely need comments to explain yourself.

Alec Flett on July 25, 2008 2:28 PM

"Not quite the same thing, unless those comments stay in the code after you've written it!"

But, that's what Steve Mcconnell suggests in Code Complete.

slapout on July 25, 2008 2:54 PM

Jeff,

If you are writing code that be consumed internally (not for public consumption), then comments can be minimal especially when you use excellent naming conventions for classes.

But when you write code others will use, it's really nice to provide many more details with your comments. I find the <example> and <code> tags to be really nice to include in documentation I have written code for others to consume. Even though I use excellent naming conventions as well.

Jonathan Starr on July 25, 2008 3:12 PM

Reminds me of a GREAT article I saw a while ago about (funny) tips for creating unmaintainable code:

17. Choose variable names that masquerade as mathematical operators:
openParen = (slash + asterix) / equals;

18. Choose variable names with irrelevant emotional connotation:
marypoppins = (superman + starship) / god;

http://mindprod.com/jgloss/unmainnaming.html

It's really the opposite of self documenting code, it's more like self-obfuscating code. :)

Dave on July 25, 2008 3:19 PM

I guess we all tend to fall into the overstated tone of Jeff's articles, but like those of Joel, that's what makes them so enjoyable and we just can't help reacting.

I think the overuse of comments if one of the 'code smells' described in Martin Fawler's "Refactoring: Improving the Design of Existing Code", and a more reasonable opinion would be at least to try to improve the code until most comments become useless. I personally spend a ridiculous amount of time trying to remove all boilerplate code and extracting every bit of logical blocks to new methods with explicit names, so I totally buy that "coding without comment" style, but only because I'm way too lazy to keep comments up-to-date, plus I think it pollutes my editor screen. But yeah, I feel guilty about that.

Vincent on July 25, 2008 4:40 PM

Me > we need to end this myth that code is EVER as clear as well-written English.

Jeff>> Really? Most of the english I read online is anything but well-written. At least code *compiles* (or interprets, if that's your cup of tea).

I submit that badly written (but semantically correct) English is STILL much clearer than non-trivial "readable" code that compiles. As someone mentioned, comments give you *context* and the *why*. Code alone NEVER gives you that.

And I'd have a hard time coming up with an example of proving the exact *opposite* point of the one being discussed than your square root approximation example. :)


Crimson on July 25, 2008 8:18 PM

A slight side-note:
"If the best code is no code, what is the best comment?"
lets think about the 'best code is no code' theory.....

Does moving your logic into a config file really make 'less code'?
What if your config file is really 'perl' expressions that get 'eval'd?

Alternately, what if the only way to record how some 'non-coding' configuration is through some umpteen series of screenshots for what buttons you clicked?

Sometimes the best code _is_ code.

Could you write something about that?
Please?
Pretty Please?

Eric on July 25, 2008 8:18 PM

One of the most important lessons I learned from my mentor is that code should be intuitive. Code could/should in many cases be self explanatory and easy to understand. Commenting isn't a bad practice, but abuse of commenting code is. I see commenting as something I do as a last option. I think of commenting code as adding spice to food; just a little is fine, but too much ruins the flavor.

Roger Wilson on July 25, 2008 8:22 PM

Sometimes a coder don't understand even a simple operation. I think comments are vital for a program :)

Omar Abid on July 25, 2008 10:59 PM

I find that adding a small description of what a method does in an xml comment block is more then sufficient. Anything more than that is just padding out your line count. :)

Jeremy Reagan on July 25, 2008 11:08 PM

---
Here is another one:

Identi-doc: Author tediously annotates each modification with their date/initials.

I don't know how many times I've seen this! Please everyone give that one up.

The Gassy One on July 25, 2008 09:01 AM
---

Oh.. this is needed for some programms for medical devices and code reviews. We have signed code for MR-Scanners.

DawnOfWar on July 25, 2008 11:47 PM

I've always felt that methods shouldn't need comments inside them, only comments describing the method should be enough.. if that even made sense

// comments go here
private void foo()
{
// not here
}

the comments are there to describe what the method does, not how it does it. How it does it can easily be seen if you look at the code

Thomas Winsnes on July 26, 2008 1:24 AM

roflmao: "Are you taking the piss mate, or were you just asleep for the last 7 years?"

I tend to feel that the member name and the parameter names should usually be (made to be) sufficient. Beyond that, RTFC.

This changes for binary-only distributions for developer clients, of course, which I almost never do. "Mate".

Atario on July 26, 2008 2:14 AM

While I'd rather have too many comments than too few, I agree that a good balance and few comments is best. It is quite obnoxious to work with developers that need to tell a story and comment every single fricking line. With spaces in between. So the simplest 5 line code becomes a whole page of tripe, and takes 3x longer to comprehend. But I'm not bitter.

boomslice on July 26, 2008 5:23 AM

This is well covered in CodeComplete, which well I guess is where you got the name of your blog from. I think Mcconnell would still say you still haven't taken it far enough.

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) );

what is r? what is n? what is t? Certainly isn't obvious. Your refactored example is still a "Coding Horror" because you are using 1 letter variable names.

Rob on July 26, 2008 10:21 AM

As a maintenance programmer, I'd replace this function with

private double SquareRootApproximation(double value) {
return Math.Sqrt(value);
}

since it's never explained why the algorithm is used over the built-in square root algorithm.

Even better, I'd replace SquareRootApproximation(r) with Math.Sqrt(r) directly and dump the function entirely.

P.S. Your code examples work better when they actually compile. Also, bounds checking might be a good idea, since you can't take a square root on a negative number without going into imaginary numbers. I believe that Math.Sqrt() returns a NaN value in this case.

Powerlord on July 26, 2008 12:40 PM

This is off topic, but I would like to suggest a blog entry subject.
I was looking what you have written about build systems and found these:
- December 06, 2004 The Magical Build Machine
- October 26, 2006 The Build Server: Your Project's Heart Monitor
After a quick read it seems you have changed your mind about the importance of build servers. It would be interesting to know how many of your old blog entries contain opinions that you have changed your mind about.

Not that there was something wrong with discarding old opinions. Just curious.

Bloodboiler on July 26, 2008 5:07 PM

Powerlord -- Miss the point much? I don't see Atwood as writing a unique function here.. he's just trying to illustrate that some random function doesn't need physical comments to be descriptive.

Anyways, I'm not sure I agree 100% with what Jeff says. In other posts he reminds us that someone else will eventually have to maintain our code. I'd like to take it one step further and say that the new set of eyes might not know what you were trying to do and that is dangerous, unless you have comments in place saying what the nondescript 'r', 'n' and 't'. I mean, would it kill you to use variables with descriptive names? Does it really hurt to put the single line comment saying what method you're using to approximate *providing* you don't overdo it?

Good post. I read your blog all the time.

Hutch on July 26, 2008 7:16 PM

Comments or not, all the extra whitespace around your encapsulations confuse me! ;)

sascha/hdrs on July 26, 2008 8:54 PM

I agree. well almost. Sometimes comments are life savers.

Just wrote an entry in my blog about all this and an incident which made me write more comments than ever...

http://code.zhandwa.com/2008/07/27/code-comments-do-we-need-them/

zhandwa on July 27, 2008 1:28 AM

@Rob

"what is r? what is n? what is t? Certainly isn't obvious. Your refactored example is still a "Coding Horror" because you are using 1 letter variable names."

r should be named root or result

t should be be eps, tolerance or precision

n is a bad variable name, because numerical coding has a Fortran tradition, in which i,j,k,l,m,n are names of integer parameters. It should be replaced by x, which is short and to the point -- you want to calculate sqrt(x).

@Thomas Winsnes

"the comments are there to describe what the method does, not how it does it. How it does it can easily be seen if you look at the code"

This is impossible to achieve in numerical code, because

x = (a - b) * (a + b);

and

x = a*a - b*b;

look equivalent *in the code* but they are not really equivalent due to floating point rounding errors. It is expecting too much from your fellow programmers to immediately recognize all the tricks you've done to increase numerical stability of your computation. Hence, it needs commenting.

katastrofa on July 27, 2008 2:18 AM

Jeff, do you think all these people write that comments are good just because they enjoy writing them?

I for one write comments because I have such a crappy memory, even with self-explaining methods variables they may not be self-explaining to me in 2-3 years. I often sit and think "why did I do this again?" finding a comment then is like finding a pearl in the muck.

TDD is a good tool for producing self-documenting functions however is not a silver bullet that replaces comments. The tests tend to be very detail oriented however it doesn't explain the thought process behind the function.

just my 2c
Anders.

Anders on July 27, 2008 4:29 AM


Jeff:

this should have been titled intention revelaing names. been around forever - the XP series of books beats on this topic to death.

mikester on July 27, 2008 8:31 AM

Suggesting that comments should be left out for "readability" is like pouring out the baby with the bathwater.

I'm a senior developer (>25 years) and I've seen code that would make your toenails curl up. The junior programmers' most favorite comments are:

- "The code is self-explanatory."
- "I didn't have time to write comments. The schedule was too tight."
- "Comments are detrimental to legibility."

I'm sorry, but if you're working on a project with over 10,000 modules containing 10,000,000 lines of code, a comment here and there isn't too much too ask.

Code routinely gets thrown away because it doesn't contain any comments, and only the original programmers know what it does.

Especially when you look at brain-damaged stream-of-consciousness code that lacks any structure or abstraction, you get cravings for comments. Otherwise, the reader might do a mark-delete and complete rewrite operation faster than the original programmer can say "Stop, I'll explain it to you!"

Spaghetti code is not just limited to C, it's also widely spread in the C++, Java and C# worlds. Bad object hierarchies, nonsensical interdependencies and so on are all around. The solution when one team is replaced by another is most often a complete rewrite, because none of the original code was documented. On the other hand, well documented code can live for decades.

Anonymous on July 27, 2008 1:20 PM

Never Start With Comments?

As with any edict, it has a grain of truth but I think misses the mark? Just refactor your comments like code. If you aren't starting with solid defined documentation then one of the best things to do is to pseudo code/comment code your functions and call flow. Then, you just refactor the comments with the code, removing out what is made self evident by the code itself. A touch of extra commenting won't hurt.

Stephen on July 27, 2008 2:52 PM

I'm so glad I comment my code extensively...it really saves me a lot of time when I have a maintenance task come up two or three years after writing a bunch of complex (for me) code. When I have some difficult code to write I begin by writing an outline, as comments, of what the code should do. It helps me write it, I leave it in, and it helps me maintain it. I can't see any reason why this is a bad thing.

Nebo on July 27, 2008 3:53 PM

/*
* FUNCTION: bitcount
* ARGS: n 32 bit container
* RETURNS: count of set bits
* DESCRIPTION: MIT Bitcount
* Consider a 3 bit number as being => 4a+2b+c
* if we shift it right 1 bit, we have => 2a+b
* subtracting this from the original gives => 2a+b+c
* if we shift the original 2 bits right we get => a
* and so with another subtraction we have => a+b+c
* which is the number of bits in the original number.
*
* Suitable masking allows the sums of the octal digits in a 32 bit number to
* appear in each octal digit. This isn't much help unless we can get all of
* them summed together. This can be done by modulo arithmetic (sum the digits
* in a number by molulo the base of the number minus one) the old "casting out
* nines" trick they taught in school before calculators were invented. Now,
* using mod 7 wont help us, because our number will very likely have more than 7
* bits set. So add the octal digits together to get base64 digits, and use
* modulo 63. (Those of you with 64 bit machines need to add 3 octal digits
* together to get base512 digits, and use mod 511.)
* This is HACKMEM 169, as used in X11 sources.
* Source: MIT AI Lab memo, late 1970's.
*
* Unit test validated on ******
*/
unsigned int bitcount(unsigned int n)
{
/* works for 32-bit numbers only */
register unsigned int tmp;

tmp = n - ((n >> 1) & 033333333333UL) - ((n >> 2) & 011111111111UL);
return ((tmp + (tmp >> 3)) & 030707070707UL) % 63;
}

smallstepforman on July 27, 2008 4:13 PM

FWIW (i know this won't get read by now), i'd advocate splitting the function into 2:

a) a public function
public double squareRootNewtonRaphson(n) {
...implementation
}

b) a private function in the module which requires it:
private double squareRootApproximation() {
return squareRootNewtonRaphson()
}

This has several advantages:
- anyone reading the application code just seens "squareRootApproximation", which is easy to understand without having to worry about implemenation details
- anyone wanting to dig further into the implementation immediately sees that it's implemented using newton-raphson
- the Newton-Raphson implementation can be added to a standard library (better still, find an existing implementation which works)
- the "squareRootApproximation" implementation can be easily switched, eg if it's found that newton-raphson is not accurate enough.

As far as comments goes, the only place i'd possibly put a comment is in the "squareRootApproximation" header, to explain why i'd decided to use the newton-raphson method in this particular case.

stephen on July 27, 2008 4:53 PM

Not all code can be obvious, especially if performance enhancements have been made. Long comments are typically there because the enhancement has made the code less readable. The aim of coding isn't to make haiku, it's to make programs work. (See @smallstepforman comment above)

Comments are also useful because hopefully it stops some loon coming along and 'fixing' it because they don't understand it's not broken.

Not all code is easy, and contrived examples always fail to impress.

The only thing better than a comment is a test, because the test should break when the code does.

tricky on July 27, 2008 6:28 PM

@stephen
I think that's a pretty good approach, the only problem would be that you might end up cluttering up the code with loads of generic to specific calls. Certainly, I can't see any way in which it could be misunderstood.
See, your comment did get read.

Tom on July 27, 2008 6:36 PM

PS It would have been better to find real code that used an approximate method because it was looking for performance enhancement over a traditional Math.Sqrt. At least it will shut people since most punters probably can't do better than the Quake Source code.

e.g. Quake's Fast Inverse Square Root
One explanation: http://betterexplained.com/articles/understanding-quakes-fast-inverse-square-root/

float InvSqrt(float x){
float xhalf = 0.5f * x;
int i = *(int*)&x;
i = 0x5f3759d5 - (i >> 1);
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
return x;
}

Since you don't require comments, I deleted them.

tricky on July 27, 2008 6:37 PM

@Anonymous
"Code routinely gets thrown away because it doesn't contain any comments, and only the original programmers know what it does.

Especially when you look at brain-damaged stream-of-consciousness code that lacks any structure or abstraction, you get cravings for comments."
But are you convinced that comments will help under those circumstances? Surely they just become part of the chaos, rather than a mitigation of it.

Tom on July 27, 2008 6:40 PM

@tricky
Looking at the article, it looks like the comments don't help with understanding.
// store floating-point bits in integer
// initial guess for Newton's method
// convert new bits into float
// One round of Newton's method
You could probably match these to the lines, even if I mixed them up. All they do is tell you exactly what each line is doing, which is pretty obvious from the lines themselves ("int i = *(int*)&x; // store floating-point bits in integer" is ugly as hell, but it's not actually unclear).
The article itself proves that it doesn't actually explain to you WHY that approach works/was chosen, or if there are any potential algorithm breakers.

Tom on July 27, 2008 6:46 PM

I have to agree with one of the arlier posters that this might be trying to hard to drive traffic to the site. The originaly comment you posted, aside from the exaggerated nonsense about SSN and "Mother's Maiden Name" was pretty reasonable. The comment explains what approximation algorithm is being used.

Comments are *not* a crutch. I've listened to you several times talk about how Intellisense *is* a crutch for you and I agree Intellisense can be a serious crutch for many but surely comments are not. If all you write are weak CRUD applications and your most complicated code resembles " txtCustomerFirstName.Text = CurrentCustomer.FirstName " then perhaps you don't need comments at all but if you're a real programmer then they can be very helpful.

Charles on July 27, 2008 7:43 PM

I disagree (partially) with your comment-removing refactoring of the Newton-Ralphson sqrt(x). You've lost the tidbit that this function is well-known and named ("Newton-Ralphson"). Particularly for numerical algorithms or implementations of other "named" constructs/algorithms, it's incredibly important to record the name of the construct in the code in order to communicate to maintenance programmers. It's not always just an issue of the code being legible.

Tom Barta on July 27, 2008 8:24 PM

I have to agree. If you find yourself commenting something, this is usually a sign that the variable or method or class (whatever it is your commenting) should be renamed to better explain what is going on. Comments are rarely kept up to date and therefore become useless and misleading.

mattcalla on July 27, 2008 9:01 PM

@Tom - the 'I deleted the comments' was just me being snarky. -1 for sarcasm.

You're correct that the comments that were added don't add much, except to a non-c programmer, as they're only explaining the how, not the why. Quick, someone convert it to language {Ruby/Perl/Python/Jasmine/Chocolate} and we can get this post well over 400 as we all bicker some more. [Drat - sarcasm again.]

Oh, and those comments aren't the comments from the source, they were added by the author of the linked article.

It was just a random article. Here's another on the same topic: http://www.beyond3d.com/content/articles/8/

For those too lazy to read,

// a 1 iteration Newton method with a good first guess; utilises knowledge of x86 hardware and float memory layout.

tricky on July 27, 2008 9:28 PM

>>Hm, you should still have a comment in that code snippet stating it uses Newton-Raphson approximation, IMHO.

I'll ditto this, and note that the second example doesn't have a function name at all, so it's a bit of a cheat to say that the third example is best (since the 2nd is obviously a function as well). Comments *should* be used to give notes on implementation details that aren't obvious from the code.

I've never even heard of the Newton-whatever approximation, so there's no way that I'd be able to reverse engineer that from looking at the code.

Bill on July 27, 2008 9:48 PM

When showing examples of the right way to write code, the author should write code that does not have bugs that can cause crashes.

The example code throws an exception when the input is zero.

lolwftcoder on July 27, 2008 11:41 PM

Thanks VERY much for this article.

Rob C. on July 28, 2008 1:31 AM

@Tom:
"But are you convinced that comments will help under those circumstances? Surely they just become part of the chaos, rather than a mitigation of it."

My whole point was that of course, when the code is commented well enough, then it is possible to keep using it, despite all the flaws it might have. If bugs are documented, they can be eliminated later on. If there's bad structure in an application, and it's documented, then it can be changed later on. Good comments in code help companies protect their investment in the source code.

However, many companies feel that commenting source code would encourage people to steal their IP. But that's not very reasonable. It's better to employ proper security measures and have properly documented code, than a mess of undocumented code (like it's most often the case) that somebody might manage to sneak out of their office. The cost of wasted time trying to understand an undocumented mess of code by far exceeds the cost of security measures.

Most bugs and wasted efforts (busted deadlines, accumulation of problems and sheer impossibilities and infeasibilities) arise only out of undocumented code.

Comprehensive manual pages should exist for every single API function in a corporate software project.

Often, a bad or outdated documentation is much better than no documentation at all. Of course, continuously maintained documentation is even better.

Anonymous on July 28, 2008 5:34 AM

@lolwftcoder

I think you would _want_ an execption to be thrown for something like that, not just return a zero...

HB on July 28, 2008 6:04 AM

Good article, point well made. Much better than that normalization post anyway! ;)

Mike K on July 28, 2008 7:02 AM

Vinzent Hoefler wrote on July 25, 2008:
>-- 8< -- snip --
>I had one project where the developer put no comments in 30,000 lines >of code. [...], and when I asked an old co-worker about it, is still in >use today.
>-- 8< -- snip --

>That's probably because no one dares to touch 30K lines of code without
>having a clue what it is supposed to do.

>SCNR.

Not true. It started at 30K lines, and when I left was ~700K lines, with about 30 changes/enhancements released twice a month. It had gone through several refactoring of various sections of code (the database access was started with Oracle 6, and was refactored for 9i). Several other sections were refactored as well. I added extensive continuous integration testing, regression testing, and enforced code standards.

Tim on July 28, 2008 7:35 AM

I get scared by people who say code isn't as clear as english. I get this image in my mind of someone trying to write a novel in a foreign language they are not fluent with. Which, of course, is the case.

Now, a particular computer language might not be particularly good about expressing certain concept -- case in point, the "why" of code. While '($phone) = $input =~ /(\d{3}-\d{4}/;' might not require any comment -- particularly if the content of $input were already described elsewhere, code doing the same thing on a language without a regex library quite likely would need some comments.

Still, if you can't read the code fluently, you are not fluent in that language. The consequences of writing code in it, then, are about the same as for human languages -- examples of which abound in the web. In fact, I have stored right here a document in english written by a chinese speaker _not_ fluent in english which will serve as the basis for some code integrating their hardware into our business. I wish I could post attachments. :-)

Once you ARE fluent, deciding what the code is pretty simple: what is not being said by the code and what the code is worse at saying than english.

I'd try to avoid describing what the code is doing at all costs. If you do that, two things may happen:

1. The code is incorrect, and you'll never catch the bug, because the comment told your brain what to expect. I have seen countless times people wasting hours and days to find a bug in 10 lines of code, only to have someone who _doesn't_ know what the code does find it instantly.

2. The code is changed, the comment is not. Maintainer's nightmare ensues.

Daniel on July 28, 2008 8:15 AM

What!!!

Here's what I think... If you are writing maintainable code that more than one person will be working with.

At the very least:
There should be a header comment that briefly describes the purpose of the method, who wrote it, and when. Then, each block of code should have a brief comment describing what it does. You should not have to look at 1 single line of code in order to find out what the goal of the method is, and the steps taken to achieve that goal.

The comments should tell the whole story as succinctly as possible. This way, someone can:
1) Read through the comments to very quickly find out what the method does.
2) Read through the code to understand all the detail.

If you just want to use the code and not necessarily fully understand and/or modify it, step 1 is a time saver. If you do need to fully understand and/or modify the code, step 1 may help you load the code into your head a little faster (particularly if the code isn't written very well, and/or it is written in a style very different from your own).

And if you want maintainable code, of course you have to maintain the comments as the code changes.

Welsh on July 28, 2008 10:00 AM

> 2. The code is changed, the comment is not. Maintainer's nightmare ensues.

Comments MAY become out of date so therefore they should never be used... huh?

If you are commenting correctly then your comments should never need to change. They will describe what the code, function, etc does - which regardless of what is inside.

HB on July 28, 2008 12:00 PM

Disclaimer: I'm probably still considered Junior level at this point

Either way, I've seen both extreme ends of code lacking sufficient documentation, and code which has excessive documentation that doesn't add anything to it.

1. Obviously, it is a mistake to comment every single line of code you write. This has been my annoyance in a lot of code that I've inherited from previous employees. For example:

/* if local preferences is null */
if (LocalPreferences == null)
/* return */
return;
/* if dynamic report is not null */
if (DynamicReportPanel != null)
{
DynamicReportPanel.SetPreferences ();
} /* if DynamicReportPanel != null */

this is a real section of code I'm maintaining... If your comment does not say anything more than the line of code itself would say if read out loud, then please don't waste the time to say it (and my time in reading it)... I have had to go to the extreme and remove all comments from certain sections of code... and it actually did help readability...


2. The other extreme of not writing comments period, is just as bad. Consider the situation as well that I have inherited code written by a senior developer which is comment-less. The methods all have very logical, explanatory names, but when it gets down to the details of what's going on, I'm left to read through and figure out what all of the rest is doing. Plainly and simply put, if you're coding in a work environment, odds are that someone else is going to have to do bug fixes or other maintenance to the code that you wrote. Stepping into a piece of code, a developer won't necessarily understand how your classes are structured, or even necessarily how your methods are put together.

3. I think the biggest problem I've been seeing with comments is the granularity of detail that they seek to explain. 99% of the time, you shouldn't have to explain a single line of code, and if you do, you should probably see if there's a more straightforward way to write it (in the examples, i do agree that some formulas are a pretty good candidate for the exception to the rule).

Sparse block comments can really help establish the functionality of a section of code without having to read and understand every single line & detail of the process, giving a brief logical overview to someone who has never touched your code before, and as such, can become a sort of map for navigating to applicable sections of code, or to get one's bearing within a particular segment. One of the comment-less pieces of code i received parses through a pretty complex tree without any note on what we're looking for at any particular level.

IMHO, if you need to comment individual lines, try refactoring, but don't neglect to give a generalized roadmap of what a particular chunk of code is supposed to accomplish...

Dave on July 28, 2008 12:33 PM

I recently saw the best redundant comment ever in aMSN's source code:

// Include the header file
#include "webcamsn.h"
#include "kidhash.h"

Me and my friends all had a good laugh at that.

Scott W on July 28, 2008 3:10 PM

I am writing thousands lines of code and they should be all mess without comments. Sure, I agree that code should be written as clear as assumed to be without comments but comments must exists.

In my opinion, readibility of code is one of the major problems and comments are part of code. It is 'in line documentation'.

It is not necessary to comment all lines, but programmer should write what (s)he intended by writing code blocks, I prefer to write comments on:
- Function / Subroutine headers about parameters and what this function does
- Long or cascaded If blocks
- Select - Case structures
- Global variables
- Name of common mathematical theorems or calculation methods

If you want to produce long living software, you should never omit writing necessary comments. I have seen several project that rewritten because of too complex structure without comments. We have redesigned and rewrite all codes from scractch instead of upgrading it because upgrading was nearly impossible, it was easier to rewrite it again.

Moosty on July 29, 2008 1:39 AM

Hi!

From my point of view there is nothing wrong with commenting your classes, methods, etc.

At least working with VS.Net it will help to use XML comments for creating a documentation in an automated way (included within a automated build process).

But I agree that there is no need to write prosa about how your code works - that should be self explaining. And using sensefull naming helps, aswell.

Juergen on July 29, 2008 1:51 AM

All of this is good discussion. It is why I enjoy the Coding Horror blog. Although I have programmed for 20 years, I have learnt much from reading responses of my fellow programmers.

Of course, everything is context. So there is not strictly one way to write comments. Sometimes we think all other programmers are in same situation as we are, with same skills, experience, and same manner of doing things. Much of reason for writing the comment is to help OTHER programmer figure out how the code was intended to work. Of course, 12 months from now, I might as well be the OTHER, when I am trying to maintain old program I have written long ago.

When I write code, I ask myself: "if I or someone else must revise or debug the code 12 months from now, how quickly will the programmer be able to figure out what the code is trying to do?" And is there chance that programmer (I or someone else) will leap to wrong assumptions and introduce new bugs when trying to make revisions to old code? Will less experienced programmer be able to quickly understand and make additions to code without wrecking it?

First I write the code to make as much sense all on its own. Then I make sure the comments fill in the important detail for the later programmer. It is important to keeping it brief and clean and keeping comments up to date, as old comments that no longer apply may confuse the later programmer. Write comments in the language of later programmer, if you know who will be maintaining the code.

Sometimes I might even write the less efficient but more maintainable code. I do this if I know that the code will more likely to be updated later, and performance is not the primary issue. As I said, everything is context. It depends on thinking through life of the code after I have done with it and making best decisions accordingly.

Vadim on July 29, 2008 5:26 AM

I have no comment

Amir on July 29, 2008 11:44 AM

I published the definitive treatment of comments in 1989:-)
A short letter: don't say that i++ adds 1 to i, but to
state what must true (but is not obvious) at that point of a program.

In the case in the article add these before the function
//Do not call if n<0
//Global t must be >0
//returns r with abs(sqrt(n)-r) < ...
(if you can fill in this blank then you don't need the comment).

RJB

RJBotting on July 29, 2008 2:46 PM

comments is good then it's right comment in right place of code,

more else good make the objects that contains not only properties and methods but and can give information about their properties and methods

TiFeSe on July 30, 2008 5:28 AM

Good variable/method/class naming is essential in making the code understandable. On the other hand there are many situations when you cannot express everything important without a full paragraph. I don't like to see 80 character method names. In my opinion 1-2-3 carefully picked short words should be enough. In time the assumptions, constraints and requirements at the time of writing become very important and they might not be obvious later during maintenance.
If anybody is interested I elaborated more on how bad comments are born in the code at http://littletutorials.com/2008/07/30/how-bad-comments-are-born-in-your-code/

Daniel Pietraru on July 30, 2008 1:37 PM

Dude, I really don't know your background, but to say something like "Junior developers rely on comments to tell the story when they should be relying on the code to tell the story." you're just perpetuating myths.

Right now I have a project that is structured like crap, no comments, but everything is well named. Trying to figure out what the original programmer wanted to do versus what it is doing is nearly impossible. A few comments with regards to the intentions of a block of code would be nice. Things fail and you're never sure if it is OK that the code is ignoring that failure, or that is the cause of the whole problem.

Good Point on July 30, 2008 3:22 PM

comments are a must
juzten
<a href="http://dailyfreesoftware.blogspot.com">Daily Free Software</a>

juzten on July 30, 2008 6:49 PM

I agree that comments need to be used in moderation. Personally, I feel that the biggest difficulty with writing too many comments is keeping them up-to-date as you refactor your code. Maybe it's just me, but I usually forget to update them.

If you try to write clear and understandable code, I think that's the most important thing.

Dan on July 30, 2008 8:12 PM

I long for the day when my problem is that there are too many comments in other people's code.

AJ Finch on July 31, 2008 3:33 AM

Problem with your fix is that you should really put some form of comment on the function, what it's for, when to use it, why, and what n is.

Roridge on July 31, 2008 4:50 AM

I agree with a lot what's being said here.
I am for code being self commenting, like using good names for the function. It doesn't matter about length of names now as the IDE makes it easier now.

Comments don't get updated as much as code. I've seen this and the result is that the comments LIE about what the code is doing!

Functions should be named and refactored so that they are doing one thing, then the code is usually small enough to just read and know.

It's always good to see comments as to why the code was wrote a certain way though if that code has some not so obvious design decisions.

But I'm sure I'm like most of you here, having to dig through legacy code with bad programming, no comments, no nice names (clickety_click being the best example recntly) and having to spend a long time just trying to figure out whats going on just to make a small change.

dean nolan on July 31, 2008 9:36 AM

Jeff, commenting on a highly subjective area like comments shows exactly why reading personal blogs are waste of time sometimes. Your posts worth while when you raise a question for discussion or stating statistical facts but posts like these waste people's time when you try to tell them how there is only one way to present comments with one example.

Samuel on August 3, 2008 4:33 PM

someone's going to shoot me if they ever have to maintain a module I wrote.

It implements a thread-safe hashtable that requires no locks on read. At the top if insert2 is a comment along the lines of

'We have the lock, now insert the record w/o disturbing things)

and at the critical moment

'Understand this line or don't touch this code.

The marked line is a no-op looking function call that prevents the optimizer from rearranging the code into a non-thread-safe version.

Joshua on August 3, 2008 8:51 PM

Tell that to my Java professor! He's enforcing comments "every 5 lines" no matter how inane. So not only do I have to suffer through Java, but also worry about losing points for not commenting enough.

//This line adds 2 and 6, producing 8
int t = 2 + 6

It's a damn shame

Joel on August 3, 2008 9:09 PM

Jeff,

I think you're opinion is really great and provides some valid points. I consider my code to be rather clean but I still make sure to usually have about 1 line of comments right before a block of code to help when I have to go back and support/update it.

My view is that comments are like a conversation with yourself reminding you of what the hell you were thinking.

Jeremy Minnick on August 4, 2008 6:02 AM

A few things come to mind when reading this article.

1. Always comment a procedure or method. Say what it does, just a line or two. Come on, how hard can it be?

2. Comment any gotcha's (e.g you must do x before doing y) or non-obvious assumptions (although assert is good for this).

3. A comment every 15 lines or so helps new readers navigate through the code. After all, you would find it hard to drive on unfamiliar roads without signposts, wouldn't you?

4. When pointers are passed in and out of functions, make it clear who owns them when the function returns, e.g.:

// Caller must free pointer returned
char *get_a_string ()

Having said all of which, I don't put that many comments in my code. Instead, I try to make the code easy to read by using sensible names and good layout.

Just my $0.02 worth. Happy coding.

Paul Sanders
http://www.alpinesoft.co.uk

Paul Sanders on August 7, 2008 3:31 PM

I don't really agree with what you are saying.

Comments in code are a real soap box for me; probably because I have wasted countless hours working through other people's code that is badly formatted and contains very few, if any, comments. I always try to comment my code well, and it annoys me greatly when other people don't.

- Re "Comments should describe the why rather than the what"
I agree with this up to a point, but if (say) I have a loop in my code which counts some stuff, I don't see a problem with putting a comment at the start of the loop such as "Count some stuff". Yes, you can work out what it's doing by looking at the code, but the comemnt saves time examining the loop itself to see what it's doing, only to forget again for the next time I look at it! the idea that code is "self commenting" is a complete nonsense put about by lazy people who just can't be bothered to do a decent job.

- A problem just as bad as poorly commented code, is badly formatted code. take your example...

----------------------------
r = n / 2;
while ( abs( r - (n/r) ) > t ) {
r = 0.5 * ( r + (n/r) );
}
System.out.println( "r = " + r );

----------------------------

Other than it not being obvious what it does (as you pointed out), the other problems with this code are...

1/ Unhelpful variable names - eg - 'r' - what the hell is 'r'? Or 'n'? These are not helpful names

2/ A personal one this, but I hate seeing the '{' at the end of a line; I find that this makes the code structure very difficult to see, especially with more deeply nested expressions. I really wish the world would move away from this convention.

3/ As demonstrated in your code, there also seems to be a trend towards not putting whitespace in code! What's all that about? All it takes is to put a blank line after a (closing) '}' and it makes the whole thing much easier to read. I'm currently working thorough a load of code that seems to have been written with the express idea of minimising whitespace. It's a thorough pain to work through (needless to say, it's also very badly commented). Another example of this is something like "for(bla=0;bla<10&&!bal2;bla++)". Don't you think a few spaces would help the readability of this example immensely?

4/ Poor type selection is also a good source of confusion and obfuscation. If you have a value that (say) indicates a "success/fail", then why not CALL the variable "fail" and make it a boolean type, rather than an integer called "r" that you assign values of zero or one to? very unhelpful. And using 'int' all the time when 90% of the time and 'unsigned int' would be much more appropriate.

I could go on, but I'll not...

Rich on August 14, 2008 6:38 AM

haha.

comments are a great source of entertainment:
here are a few of my favorites

' * I'm falling asleep at the keyboard, so no telling how much sense this makes....
(huh? wait... wake up buddy!)
----------------------------------
%REM
/**
*PURPOSE:Blackbox handling of getting the database by repID
* which is pretty stupid when you consider Lotus has
* this all handled in the openByReplicaID except the ermsg
* ...but it is better than the current 8 subs doing virtually
* the same thing and a line savings of about 24 lines + code
* reuse. (all savings are now lost in this documentation though)
*HISTORY:
**/
%END REM
----------------------------------
*PURPOSE:Hack code to turn a full name parameter into more parts for
* firstName lastName (and more) processing.
(well at least I admitted it)
----------------------------------
%REM
What is this CRAP!!!
A script library with nothing but 2 globals in it...
to make the generic 'session' as a global is really bad.
Very weak
Very Very weak
%END REM
(so how do you really feel about it?)
----------------------------------
*NOTES:
* 2005.11.21 -raw- THIS FUNCTION IS A PRIME CANDIDATE FOR REFACTOR AND THE SMARTFRAMEWORK
* CLASS HAS BEEN STUBBED TO START MOVING THIS STUFF IN.
* 2005.11.30 -raw- THIS FUNCTION EXISTS ONLY TO CAPTURE AND INVOKE REQUIREMENTS QUICKLY
* AND NEEDS TO BE REFACTORED FOR SUPPORT AND SPEED CONCERNS.
(never got around to that refactor)
-----------------------------------

endInit:
Exit Sub

HandleError:
' * AAARGH!! Dammit! Somebody needs to cut Wayne's fingers off!!!
' * What sections of code are those line numbers for????
errMsg = "Line " + Cstr(Erl) + " of 'Initialize' (" + Cstr(Err) + "): " + Error$
Call agentLog.LogError(agentLog.Numerrors, errMsg)
If Not curDoc Is Nothing Then Call agentLog.LogAction("[Processing doc with UNID = " + curDoc.UniversalID + "]")
If Erl > 117 And Erl 164 And Erl 230 And Erl 112 And Erl 79 And Erl &lt; 283 Then
Resume endAllDocs
Else
Resume endInit
End If
(Well, hotrod... just rollback, annotate the code, and then make your updates... hee hee)

rwheadon on August 14, 2008 6:23 PM

Here's another fun one I found yesterday.

/** Timeout for response in ms */
public static final int DEFAULT_TIMEOUT = 40000; // This is arbitrary, no reason I chose this
...
synchronized (sem)
{
try
{
log("Waiting for response");
sem.wait(DEFAULT_TIMEOUT);
} catch (InterruptedException e)
{
log("Caught InterruptedException waiting for response: %s", e);
}
}

Yo Yo! on August 22, 2008 5:29 PM

You're CHOOSING to be irritated about something of no consequence as an excuse to distinguish yourself as a commenting ninja.

Lots of verbose commenting is FUN and makes coding EASY!!!

YAY for FUN!!! YAY for EASY!!! YAY for COMMENTS!!!

Only an idiot would lose sleep over whether their comments aren't as hip or succinct as someone else would like.

Next post: "RTFM NOOB!!!"

Noob on August 24, 2008 11:05 AM

I can't believe what I'm reading with some of these comments. Do you people who advocate using zero comments actually work at real companies that make real software?

You realize other people are going to have to read your shitty code eventually right? (and if you are the kind of person who thinks you don't need to write ANY comments then I assure you everyone else thinks your code is shitty) When I have to fix a bug and the person who originally wrote the code didn't have the courtesy to write a few comments I want to break things.

Sensible Developer on September 9, 2008 7:09 AM

It makes good sense to put in comments indicating exactly what part of the code has been changed, by whom, on what date, and for what reason. Put in the project number, ticket number, or whatever else is relevant. That way, if a bug fix affects something else later on, or has to be refined further to account for changes in the real-world requirements, you can save the next person a lot of time and effort.

1389 on September 12, 2008 10:36 PM

I have come back to this article several times, because it sounds a lot like what the XP methodology uses. Each time I end up thinking that at first glance this sounds like a great idea, but in practice it just doesn't work. Source code is not a replacement for documentation.

Corey Furman on October 3, 2008 9:38 AM

I think the real issue is not comment are good or bad.Issue is how we use comments in code.
I believe on the importance of commenting in code.It saves time, clarify complexities, easier maintainability and make code "fresh cream cake" for other team members including new comers. Let me explain this. Say, If I am writing a code, actually i am not remembering it.I am just using logic from my mind and developing a software.After 3/4 weeks when I review my own code, I will not able remember exactly what area of code doing what (if its a bulk code).At that time self-explanatory naming convention and comments describing the whole story in files will help me to understand it quickly. Thus, I will not use my brain resources on useless effort to recall on own hand-written code and keep my mind fresh :)

basitjee on October 9, 2008 3:40 AM


Bastijee, check out the Fowler refactoring book on extract method / method naming. Jeff mentions this refactoring above. You might code even faster (and do less rework) if you type fewer comments : )

Whenever we make an assumption about the external domain - something not intrinsic to the code - then a comment helps spread the knowledge to other guys on the team!

// Null relation Id => uber account
if (!account.RelationId.HasValue)
{
account.Name = String.Format("<strong>{0}<strong>", account.Name);
}

Ken on November 14, 2008 3:40 PM

I have a really horrible memory, so as I go through a piece of someone else's code I like to write down what each piece of code does, otherwise I would forget. I find the best place to write down what a piece of code does is as a comment sitting right next to that piece of code. Generally as I work through code, I insert one comment for about every four lines. or five or six if there is nesting. These comments each tell what that little block of code does. When someone will not allow me to add comments to their code that is like saying I'm not allowed to understand it. Conversely, I have been complemented by people who say that my commenting is useful and valuable.

Not everyone thinks the same way. Someone who says code should not be commented is an elitist way of saying that there are certain programmers who should not be allowed to program because they don't think the right way. Programming is a tool. It is the way we embed our thoughts in technology. If we prevent commenting, we lose the value that people who need to comment can provide.

Jon Grover on December 5, 2008 4:35 AM

Hello..this is angel visiting first time to this site and find it very interesting.


-----------


Angel

[url=http://www.casualdate.net.au/melbourne-dating-agency]Dating Melbourne[/url]

angel on March 19, 2009 4:24 AM

How about using a program that can condense comments. They can be as detailed as the person wants it to be, and it won't clutter the code. I personally use very little commenting, but I'll comment information about what the function/class does at the top of it in simple terms. The more modularly you program, the nicer it becomes - within reason.

Gage on June 5, 2009 4:13 AM

There are some interesting points in this article, and particularly in the responses to it. In fact I think it's worth pointing out that a more thorough understanding of the issue can be found by reading the extensive comments on this article. :P

Thomas Foss on July 16, 2009 1:43 AM

well, that is good to knwo

supra skytop on July 30, 2009 12:14 AM
Content (c) 2009 Jeff Atwood. Logo image used with permission of the author. (c) 1993 Steven C. McConnell. All Rights Reserved.