Coding Without Comments

July 24, 2008

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
267 Comments

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 7:37 AM

@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 7:40 AM

@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 7:46 AM

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 8:43 AM

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 9:24 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 9:31 AM

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 10:01 AM

@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 10:28 AM

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 10:48 AM

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 12:41 PM

Thanks VERY much for this article.

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

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 4:10 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 6: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 7:04 AM

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

Mike K on July 28, 2008 8: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 8: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 9: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 11: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 1: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 1:33 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 2: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 2:51 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 n0
//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 3:46 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 6:26 AM

I have no comment

Amir on July 29, 2008 12:44 PM

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 2:37 AM

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 4:22 AM

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 6:28 AM

comments are a must
juzten
a href=http://dailyfreesoftware.blogspot.comDaily Free Software/a

juzten on July 30, 2008 7:49 AM

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 9:12 AM

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 4: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 5: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 10: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 5:33 AM

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 9:51 AM

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 10:09 AM

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 7: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 4:31 AM

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;bla10!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 7:38 AM

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 6:29 AM

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 12:05 PM

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 8: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 11:36 AM

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 10: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 4: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 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 5: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 5: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 2:43 AM

well, that is good to knwo

supra skytop on July 30, 2009 1:14 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 February 6, 2010 10:38 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 February 6, 2010 10:38 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 February 6, 2010 10:38 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 February 6, 2010 10:38 PM

You're a year late Jeff...

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

Jason Monroe on February 6, 2010 10:38 PM

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 February 6, 2010 10:38 PM

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 February 6, 2010 10:38 PM

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 February 6, 2010 10:38 PM

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 February 6, 2010 10:38 PM

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 February 6, 2010 10:38 PM

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 February 6, 2010 10:38 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 February 6, 2010 10:38 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 February 6, 2010 10:38 PM

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 February 6, 2010 10:38 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 February 6, 2010 10:38 PM

It's a shit-ton easier to dive into random code when it's got neat line-by-line comments (within reason, but anything potentially confusing should be commented). Lot's of comments aren't an excuse for bad coding practices, but there's no reason not to include them. Space is cheap and you can always globally turn them off from being displayed if it irritates you that much.

Tempaccount767 on April 25, 2011 5:14 AM

Hello. Jeff. these comments are as a prototype of the codes and to get my idea of the code out.
Mass Profit Formula Review

Muhammad Ismail on June 28, 2011 7:43 AM

«Back

The comments to this entry are closed.