Code Tells You How, Comments Tell You Why

December 18, 2006

In an earlier post on the philosophy of code comments, I noted that the best kind of comments are the ones you don't need. Allow me to clarify that point. You should first strive to make your code as simple as possible to understand without relying on comments as a crutch. Only at the point where the code cannot be made easier to understand should you begin to add comments.

It helps to keep your audience in mind when you're writing code. The classic book Structure and Interpretation of Computer Programs, originally published in 1985, gets right to the point in the preface:

Programs must be written for people to read, and only incidentally for machines to execute.

Knuth covers similar ground in his classic 1984 essay on Literate Programming (pdf):

Let us change our traditional attitude to the construction of programs: Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do.

The practitioner of literate programming can be regarded as an essayist, whose main concern is with exposition and excellence of style. Such an author, with thesaurus in hand, chooses the names of variables carefully and explains what each variable means. He or she strives for a program that is comprehensible because its concepts have been introduced in an order that is best for human understanding, using a mixture of formal and informal methods that reinforce each other.

If you write your code to be consumed by other programmers first, and by the compiler second, you may find the need for additional comments to be greatly reduced. Here's an excellent example of using comments as a crutch:

This is a snippet of code from a well funded, closed-source system that has been deployed in production for years.

float _x = abs(x - deviceInfo->position.x) / scale;
int directionCode;
if (0 < _x && x != deviceInfo->position.x) {
  if (0 > x - deviceInfo->position.x) {
    directionCode = 0×04 /*left*/;
  } else if (0 < x - deviceInfo->position.x) {
    directionCode = 0×02 /*right*/;
  }
}

This is equivalent to the following, more readable code, with a bugfix.

static const int DIRECTIONCODE_RIGHT = 0x02;
static const int DIRECTIONCODE_LEFT = 0x04;
static const int DIRECTIONCODE_NONE = 0x00;
	
int oldX = deviceInfo->position.x;
int directionCode
  = (x > oldX)? DIRECTIONCODE_RIGHT
  : (x < oldX)? DIRECTIONCODE_LEFT
  : DIRECTIONCODE_NONE;

Note that more comments does not mean more readable code. It didn’t in this example. The comments in the snippet above-- if you even noticed them-- only clutter the code even more. Sometimes fewer comments makes for more readable code. Especially if it forces you to use meaningful symbol names instead.

Although there are almost infinite opportunities to refactor and simplify code to obviate the need for comments, explaining yourself exclusively in code has its limits.

No matter how simple, concise, and clear your code may end up being, it's impossible for code to be completely self-documenting. Comments can never be replaced by code alone. Just ask Jef Raskin:

[code] can't explain why the program is being written, and the rationale for choosing this or that method. [code] cannot discuss the reasons certain alternative approaches were taken. For example:

/* A binary search turned out to be slower than the Boyer-Moore 
algorithm for the data sets of interest, thus we have used the more 
complex, but faster method even though this problem does not at 
first seem amenable to a string search technique. */

What is perfectly, transparently obvious to one developer may be utterly opaque to another developer who has no context. Consider this bit of commenting advice:

You may very well know that

$string = join('',reverse(split('',$string)));

reverses your string, but how hard is it to insert

# Reverse the string

into your Perl file?

Indeed. It's not hard at all. Code can only tell you how the program works; comments can tell you why it works. Try not to shortchange your fellow developers in either area.

Posted by Jeff Atwood
55 Comments

Thank you for your blog--i read it almost every day and find it informative and interesting.

Sometimes when i'm writing code, i think "i should comment" this--only to realize that the comment is needed because it's not clear how it works.

comments i gravitate to now are those that say "why" or indicate the intent of the code.

MikeP on December 19, 2006 6:07 AM

I always ask myself, "What questions would be asked by someone looking at this code for the first time?" And then I write comments to answer those questions.

Scottford on December 19, 2006 6:50 AM

Sometimes when I'm writing code, I think "I should comment this"

Right. The first and proper response to that feeling is to *roll up your sleeves and refactor the code*. After you've refactored, if you still feel a comment is necessary, then by all means add one. Never comment before you've attempted to refactor away the comment first.

Jeff Atwood on December 19, 2006 6:52 AM

I couldn't agree more. Like the man says, if the code needs comments to explain what it's doing, it isn't done yet.

Kevin Dente on December 19, 2006 6:58 AM

Two points:

1) You are absolutely right - comments should describe the thinking behind the code, not the code. Especially important are decisions that were tried and failed.

2) Your example of a good comment sucks. :) It's describing the code, not the thinking behind it. If you need context for the reverse string operation, why not write a "reverse" method?

A better comment might be "Reverse the string as a weak obfuscation technique" (for example)

Robert on December 19, 2006 7:04 AM

Eric Lippert had related posts on the same topic:

http://blogs.msdn.com/ericlippert/archive/2004/05/05/126739.aspx
http://blogs.msdn.com/ericlippert/archive/2004/05/04/125893.aspx

JD

JD on December 19, 2006 7:08 AM

As always, excellent. Right to the point and informative.
In favor of comments vs. no-comments, with the advances in IDE, most offer syntax highlighting these days.
Sometimes, while reading a sequence of black and blue (standard VS colors), having a a line of green in the middle makes it jump out.
The reverse goes of course... too much green kills the green.

Eric Liprandi on December 19, 2006 7:12 AM

I agree with Robert. If I have to write comments like "# Reverse the string" its going to end up with more comments than code. If a developer considers that to be opaque they're better off not even trying ...

Dave on December 19, 2006 7:53 AM

Dave, as pointed out in the early part of the article, comments should be useful not primarily for the person who writes them, but for those who read them.
While the example given may not be so obvious for most Perl programmers (experience level?), it may not be that obvious to non-Perl savvy programmers.
And it is possible that some may, one day, want to convert that particular program to a different platform or language. In that particular case, it is very likely that the person who reads the comments (the intended audience of comments after all), is mostly interested in the "what?" and not the "how?".
And from personal experience, my coding style does evolves, impacted by several factors, including platform evolution, language evolution, experience. If I look back, I may not write the same line(s) of code to do the same thing months or years later.

In general, the amount of comment needed for a line depends on its complexity.
int i = 0;
Does not need comments.
return new ObjectEl(Math.Max(arg1, arg2), RetrieveObect(arg3, DB_NAME))
probably would require a comment. Even better, as suggested in by Jeff and other poster, it could be re-written to be self explanatory.
Writing compact lines of code does not produce compact code or faster code... leave it up to the compiler. But I guess that's a whole different article (Jeff ;)

Eric Liprandi on December 19, 2006 8:18 AM

ugh. since when did writing code become intertwined in the eccentric world of art. Suggestion. If you've hired programmers that are too stupid to read either the comments or the code, you're SOL. If I hired someone that wasted their valuable brain power on this nonesense we'd never get anything done, and I'd most likely fire the guy on the spot. Leave this eclectic crap to abstract spatter paintings and religious philosophical banter whilst sipping wine by the campfire.

Johnny on December 19, 2006 8:24 AM

Johnny, every line of code is read several times but written only once. Spending the time upfront to make it readable and understandable is a direct productivity gain.

Robert on December 19, 2006 8:38 AM

If you need context for the reverse string operation, why not write a "reverse" method?

Touch.

Couldn't agree more. I wrap a lot of "weird" code like this with well-named functions.

Jeff Atwood on December 19, 2006 8:39 AM

I found the comment above interesting, having worked on projects where the attitude was "Don't waste time on structure or commenting, do it at the end" and seeing code written that was good enough simply because it worked, I have found that you're exactly right. Coming back to the code even weeks later it was incromprehensable, even with an understanding of what the intention of the programmer was. There's nothing quite like seeing "int temp1 = ..." to confuse the hell out of anyone trying to read what you've done.

I would suggest that Johnny reconsider his management style if that's his approach; good code structure should be encouraged by management. It takes a little longer now, but in 1 or 2 years when the system breaks down and you need to get a guy in to fix it, you don't want him to be wading through meaningless variable names and weird program structure just to fix a simple mistake.

Greg Poole on December 19, 2006 8:52 AM

As a side note, that Perl example makes an argument, but not the one the surrounding text implies. In fact, it might fit higher up in your post, because the correct way to reverse a string in Perl is vastly simpler:

$string = reverse $string;

The join and split operations were probably cargo-culted, and it was the very act of cargo culting that left an obfuscated mess that requires a comment.

Sometimes the best way to be clear when programming a particular language is to learn the idioms of that language well.

Of course, this is Perl, and "baby talk" is explicitely allowed -- everyone has to start somewhere. :-)

Geoff Broadwell on December 19, 2006 8:53 AM

I do wonder about this non-comment fetish.

When I was taking programming classes in college, we got hammered if our code was not commented. The idea was to have the how and the why in it, such that it was easy for the grader to skim through the code and tell if it was correct.

Of course, this had a lot of push back from the students who hated wasting time on it. But it did produce code that was understandable by novices.

DrStankus on December 20, 2006 2:42 AM

I might have commented on this, but it seems superfluous.

daniel on December 20, 2006 4:51 AM

Well...I hate to have to point this out, but the double use of ?: in that example just highlights a bad coding technique. How much clearer would it have been NOT to use the horror that is ?: ?

Brook Monroe on December 20, 2006 4:54 AM

My guess is that should be:

# reverse a string word-by-word
$string = join(' ',reverse(split(' ',$string)));

John Hascall on December 20, 2006 5:57 AM

Ha, perhaps we were both screwed by your blog software - those should be quote space quote
not quote quote.

John Hascall on December 20, 2006 5:58 AM

Ha, I (and maybe you) got scrwed by your blog-software eating our spaces. Those should be quote-space-quote not quote-quote.

John Hascall on December 20, 2006 5:59 AM

One use for comments raised in a code review:
searchable string for maintainance. We're all familiar with //FIXME, but how about

//Defect v4.04#112: customer wishes amounts above
//MAXAMOUNT reduced to max and processed

to identify where and why but not how
if( amt MAXAMOUNT ) amt = MAXAMOUNT;

I accepted this suggestion to improve maintainance; your comments?(I know, all CAPS is EVIL, but...)

dave on December 20, 2006 6:36 AM

Martin Fowler makes the observation that code comments, while not strictly a code smell, can be used as a deodorant for code smells. Frequently, they're an indication that something needs refactoring. It's not that they are bad, but lots of times they are used to account for poorly factored code.

Dave P. on December 20, 2006 6:47 AM

Said better, while not ignoring this is still very much an issue of preference: http://c2.com/ppr/wiki/WikiPagesAboutRefactoring/CommentCostsAndBenefits.html

$reversedString = blah blah blah

is IMO better, and more concise

Izaak on December 20, 2006 6:56 AM

Good point. I use comments as notes to myself as much as notes to others. It's not just the 'why', but also what I'm thinking at the time. That way, when I have time to refactor that portion, it's a bit easier. I hate looking at code I've written and thinking, "What the hell was I thinking?"

cloggins on December 20, 2006 6:58 AM

"$string = join('',reverse(split('',$string)));

reverses your string, but how hard is it to insert

# Reverse the string "

Well, thank goodness. At least you are ok with some comments on "what the code does".

This has become such a dogmatic thing these days...just like so many other decent ideas, they are horrific when taken too far.

I certainly don't mind a comment telling me what it was supposed to do, as well as how. Can make it easier to debug if it breaks later. At least you know what the intent was, and you can see if it matches.

DrStankus on December 20, 2006 7:38 AM

It always amazes me how arrogant so many programmers are.

"if the code needs comments to explain what it's doing, it isn't done yet"

"obviously you don't expect your code to be read by someone who isn't familiar with the language syntax"

"If you've hired programmers that are too stupid to read either the comments or the code, you're SOL"


It is not always feasible to have a programming guru on hand to fix every issue. Not everyone has the same skill set. Sometimes companies are stuck having to maintain code in languages their current staff aren't well-versed in. Gurus aren't available either at all in some areas, or for the money some companies have alotted for their IT staff.

People should assume someone with 1 or 2 years experience will be coming in after them to maintain their bugs. I'm not saying you have to explain every little detail, but if you have any doubt whether someone coming after you will understand your code in fairly short order: add a comment. Don't be an ass and assume they should understand the entire context and layout of the application the way you do, or that they have a few days/weeks to get oriented to confidently fix your bugs.

Black Warrior on December 20, 2006 7:56 AM

I agree that clear code is better than comments and usually should be sufficient. If it isn't sufficient, think about what you're doing (could I simplify this?) instead of just adding the comment. Sometimes the comment is still needed, but often the best solution is to just simplify the code or improve a variable name.

There is one thing I would like to add to this post. Comments are also good for summarizing. Even when the code is commented and crystal clear, it isn't enough. Somebody unfamiliar with the codebase shouldn't have to wade through the whole file to figure out how a class fits into the system.

There should be a header at the top of the file explaining the purpose of the file. There should be a header before every function explaining the purpose of the function.

C# and Java both have language support for this. Our team has internal requirements for these headers, and it makes debugging much easier.

Doug on December 20, 2006 8:12 AM

Good code, using human-readable variables, generally comments itself. The only time I over-comment code is when I'm showing data flow to a complete newbie that has no idea what's happening at all. Many times it is their first experience with seeing code.

Mostly, though, your operations should indeed be self-explanatory. My own code is still readable to me many months later, because the fellows that taught me how to code (in HyperCard, no less), were professionals that made sure it was drilled into my head.

More often in my code you'll see variables like:

subInfo
subPhone
subAddr

than you'll see

si
sp
sa

While the latter is easier for me to type, thus making me a faster programmer, the former is easier to read, thus making it easier to change the code later and read teh code later. I'd say a little typing up front saves in the debug process later. I think that's a lot of why I don't pick up new languages quickly anymore. Too many examples are given in the shortest, most efficient way possible, rather than the most humanly readable way possible.

Jae on December 20, 2006 8:24 AM

If you need context for the reverse string
operation, why not write a "reverse" method?

Couldn't agree more. I wrap a lot of "weird"
code like this with well-named functions.

That still doesn't say *why* you reverse the string.

A good comment, IMHO would be like:

# reverse the string, because [foo]

Even if you created a reverseString subprocedure.

Joe Grossberg on December 20, 2006 9:10 AM

At my current job I've had a number of predecessors of various skill level, none of whom I've met. One guy had a blunt-force style. His code was fairly easy to read because I don't think he actually knew any algorithms. He had a bad habit of commenting EVERY SINGLE LINE OF CODE IN ALL CAPS. Maybe 1 in 100 comments could be deemed minimally useful in some way. At the end of every function he had, I shit you not:

# RETURN TRUE.
return true;

I wish I had his email to send him this article.

Gabe da Silveira on December 20, 2006 9:11 AM

While I agree that your code should be refactored enough that it is very easy to read I do not think that good code should replace the use of comments. I still firmly believe that each logical block of code should have a comment explaining it. Even if you think it is extremely obvious.

int oldX = deviceInfo-position.x;
int directionCode
= (x oldX)? DIRECTIONCODE_RIGHT
: (x oldX)? DIRECTIONCODE_LEFT
: DIRECTIONCODE_NONE;

That is well written code, but who has any clue what that is doing? There should be a comment above that explaining what is going on.

Billkamm on December 20, 2006 9:24 AM

http://www.google.com/uds/js/uds_compiled.js - does this follow SICP's statement about program?

Just-a-speck on December 20, 2006 11:01 AM

I avoid writing comments - it yields good job security! if no one else can read your code, they gotta keep ya. ;)

kidding aside, where I work, the only comments i've found from my predecessors are:

1. comments i've written
2. comments that merely say something like "Don't modify anything below this line" when the junk below that line has been deprecated.

I believe this site to be of use:

a href="http://thc.org/root/phun/unmaintain.html"How to write unmaintainable code/a

David on December 21, 2006 6:35 AM

I definitely agree. Good code needs basically zero comments. About the only time I use comments these days is to document an algorithm or external things.

Loren Pechtel on December 21, 2006 10:03 AM

If you want a reasonable example of well documented code, take a look at the Java API. All the code is available.

I've never felt in any way stuck or confused when reading even the most complex piece of code in the Java API--it reads like a children's book.

You may think you don't need it THAT digested, but it sure helps! When you are just glancing into someone else's class to make YOUR class work--you really don't want to waste time understating their garbage--you just want to understand some operational detail that isn't obvious from the API.

I don't believe I've seen one yet that had more code than comments (and I'm just talking inline comments, not javadocs)

What is the argument against good comments? They help you revisit code for a self-review which you should be doing anyway. If they slow you down, either you aren't thinking enough in the first place or you need a typing class.

Know how when you are explaining a problem in your code to someone else, you often come up with the fix yourself? Comments also act in this capacity--problems requiring refactoring that you don't see at first come out very clearly when you try to explain your code in comments.

Also don't use something like this:

"if the code needs comments to explain what it's doing, it isn't done yet"

The "What It's doing" phrase simply means don't repeat your code in comments (which is correct). However, that doesn't cover all the Why issues you should be putting in there.

Every time I encounter code and can't talk to the person who coded it, I have to start thinking "Why" did he make that choice? Was he more insightful than me, or am I seeing something he missed.

Here is an example from some code I've been working on. A string number without a decimal is being multiplied by another number that "Tends" to be a factor of 10. The code currently converts it to a BigDecimal, multiplies it by the factor and converts it back to a string.

This is taking up a lot of resources on our embedded application.

Furthermore, the unit tests pass in numbers like 3333 instead of a factor of ten to multiply by.

No comments whatsoever exist because the writers were "XP" and would always be able to talk to each other.

Now the writers are gone.

I can improve the hell out of this by simply moving the decimal back and forth within the string and never converting it.

But WHY the 3333 test? Could some caller (this is called from ALL OVER the place) be using arbitrary numbers to multiply/divide by?

Why the conversion to BigDecimal? Were they not smart enough to understand the fact that BigDecimal tends to allocate bunches of byte arrays, or am I totally missing something?

When the big decimal is formatted to a string it has a min/max decimal places, how is this "MinDecimal" being passed into the method interacting? Which takes precedence?

So instead of a simple refactor, this becomes running all over the program to find out WHY things were done and how many different choices I had.

btw:

I ended up refactoring the method but leaving the old one there--if the value passed in isn't a power of ten or something really tricky happens, it falls back to the original. I've never seen this happen yet except in those stupid arbitrary tests.

Bill on December 21, 2006 11:08 AM

Your post is contradictory.

RedMatrix on December 22, 2006 2:01 AM

The no-comment fetish has come about because comments have to be taken as being incorrect or wrong and as such thoses long blocks of comments are usally worthless.

As code is changed comments are more often then not, not updated also you don't know if the comment was made before the code was written so it is now out of date, and thoses are just two of the ways comments differ from what the code actually does.

Since it is very common for code to differ from what the comments say it does whenever you have to change some code do you read all thoses comments or ignore the large comments and follow the code?

will Dieterich on December 22, 2006 5:32 AM

Better:

sub reverse_string {
my $string=shift;
return join('',reverse(split('',$string)));
}

$x=reverse_string("don't repeat yourself, even in comments");

Some comments are good (like the Boyer-Moore comment above) but often comments are a "bad smell"... a lot of programmers only write comments to apologize and make excuses for things they know are wrong.

[... i'll punish you ...]

Javadoc-style comments, which explain the function of objects and methods, are often less than effective. For instance, all of the AWT components in Java have methods called invalidate() and validate(). The Javadoc said that invalidate() "invalidates the component" and that validate() "validates the component". There was no explanation of what validation and invalidation where, but programmers found they had to do something with those methods if they wanted applets to repaint correctly.

I don't think that programmers have trouble understanding what objects and methods do, taken individually. The trouble is that, in a a system with 50 objects, programmers have a hard time understanding which one to use, how the objects fix together, and where the right extension point is to make the change they want to make. I haven't seen the right tool for that job yet.

Sailor Moon on December 27, 2006 4:02 AM

Me can't wait for when natural language programs won't not make code not unreadable.

OneMist8k on January 3, 2007 6:07 AM

I've always said "WHY" is the most important thing to comment, and always gotten static over it. I usually include a file, or big comment block somewhere where it makes sense, that just states the purpose and general design philosophy of an application, and any important assumptions in force.


All that aside, I've actually noticed a trend in a lot of developers to actively NOT READ COMMENTS. Whether because they are used to comments being bad, inaccurate, out of date, nonexistent, or maybe they just don't like to read seems to vary, but on many occasions Ive been asked to assist someone figure out some old code or another, and figured out their problem just by reading the comments and groking the intent of the code rather than trying to read every last line of it.

Another related trend I've noticed is a tendency to rely too much on debugging to figure out what code does rather than interpreting it mentally while reading thru it. I've watched too many developers go line by line in a debugger when simply looking at the code, a call chain, some names, and a comment or two is usually sufficient to pinpoint an area that is likely to have problems.

And finally, my big pet peeve is when developers make code changes to legacy / older code and make no comment that they are making a change or WHEN or WHY they are making a change. Source Control is great and all that, but I'd rather not have to review all possible versions of a file directly to ascertain when a change was introduced and for what reason if I have to reconstruct how something bad was permitted to happen in PROD, how long it was possible for it to occur, and what else was affected.

Often the most useful comments are the ones that have little to do with the code itself and more to do with flagging bug fixes and functionality changes with a date and a justification (even if its just a reference to a bug tracker system or ticket).

Shrike on March 18, 2007 1:03 PM

What do you really think is easier to read?

int directionCode
= (x oldX)? DIRECTIONCODE_RIGHT
: (x oldX)? DIRECTIONCODE_LEFT
: DIRECTIONCODE_NONE;

or

if (x oldX)
nbsp;nbsp;directionCode = DIRECTIONCODE_RIGHT;
else if (x oldX)
nbsp;nbsp;directionCode = DIRECTIONCODE_LEFT;
else
nbsp;nbsp;directionCode = DIRECTIONCODE_NONE;

I actually prefer the second version.

KG on September 7, 2007 1:52 PM

KG, you misaligned the first version, while you nicely aligned the second one. that's not fair. take this

int directionCode
= x oldX ? DIRECTIONCODE_RIGHT
: x oldX ? DIRECTIONCODE_LEFT
: DIRECTIONCODE_NONE;

i actually think this is much more readable than the if/else thingies.

litb on March 7, 2008 1:03 AM

The problem with your ternary operator example [ i.e. (condition) do_true : do_false ] is the same as the problem with one-line-if's.

If you recall, in C-ish languages you can have something like:

if (condition)
``do_true
else
``do_false

So, How do you interpret:

if (condition1) if (condition2) do_true else do_false

is it:


if (condition1)
``if (condition2)
````do_true2
else
``do_true3


OR:


if (condition1) {
``if (condition2)
````do_true2
``else
````do_true3
}

Before you think it's obvious, realize that in BOTH examples the ``if'' operator has more than one subsequent line after it. Neither are, intuitively at least, ``one-line'' if's. Convention says to use the second construct, which is even framed by the rule: ``else'' matches the closest ``if.'' Note that, if not for this rule, the original sentence would be a member of a language generated by an ambiguous context-free grammar. The decision is entirely semantic. If you feel it's obvious then it's only because you've been in the game for a long time. When you write code, it is potentially around for generations. (There is still COBOL floating around out there-- it is STILL alive). Don't take language shortcuts for granted. Use the ternary operator in truly unambiguous situations only. In fact avoid using it, if you can. Use WORDS not SYMBOLs. There are already enough symbols. Turn on your coding verbosity!

krundo on October 25, 2008 2:56 AM

This is something i don't understand at all - commenting code is damnably good practice - why do so many developers see it as a sign of weakness? Do you *know* your language inside out like keanu reeves *knew* kung fu in the matrix? Do you not own any reference books? No bookmarks to developer sites? Comments can be seen as a local reference; explaining the why of a piece of code in a local context.

I was actually told today, after inquiring as to why there were no comments in a class - 'well, if you're too stupid to understand it i can add some comments'. No one want's to parse a code file in their head - comments let you blitz through some code, seeing what it does at a glance.
And if you do feel the need to decry commenting, a word of warning: there is no way you can without coming across, at best, as arrogant, and at worst as the worst type of socialogically maladjusted retard.

riss on November 5, 2008 5:35 AM

Hi all. Everything has its wonders, even darkness and silence, and I learn whatever state I am in, therin to be content
I am from Oman and know bad English, please tell me right I wrote the following sentence: Subscribe to our newsletter and receive our exclusive special report on airline ticket.

Thank :p Sheehan.

Sheehan on May 7, 2009 8:59 AM

Sorry. Men of genius do not excel in any profession because they labor in it, but they labor in it because they excel. Help me! Need information about: kitchen islands. I found only this - a href=http://kitchen-islands.info/Freestanding-kitchen-islands/Kitchen-islands-with-caster/Kitchen islands with caster/a. A list of some of the current travel deals for cheap airline tickets. Where do you guys usually get cheap airline tickets. Thanks for the help :o, Nick from Pakistan.

Nick on May 9, 2009 8:54 AM

Sorry. If you believe the doctors, nothing is wholesome; if you believe the theologians, nothing is innocent; if you believe the military, nothing is safe. Help me! Could you help me find sites on the: Costumers faq about airline tickets, airfares and fligths information your booking and ticket details are kept securely in the airline computer system.. I found only this - a href=http://kitchen-islands.info/Kitchen-islands-table/Build-a-kitchen-island/Build a kitchen island/a. Danny travel offers discounted economy and business class tickets from anywhere in the united states to belgrade, zagreb, sarajevo, dubrovnik, budapest, vienna. Globesterairline tickets llc. With respect :o, Graham from East.

Graham on May 10, 2009 3:05 AM

Code should be documented using uml, data dictionaries, other diagrams etc.It is not productive to search through code, it is better to design ,prove your algorithm-solution in paper and then proceed to implementation. Not to mention that there must be always specs explaining the purpose of every element.

AAD on May 25, 2009 2:05 AM

Every code section I write I end with the comment "Because I said so"

Also, occasionally I come across uncommented code and I do the right thing and add comments to explain the why. "Because they said so"

This system has never once failed to explain why something was coded as it was.

Pro on July 13, 2009 2:26 AM

Are you so sure about your example?

Try it when scale=(-1)

Or when x=4 and position.x=(-4)

Do you think your new-and-improved code gives the same results?

Joel Parker Henderson on February 6, 2010 9:51 PM

"Well...I hate to have to point this out, but the double use of ?: in that example just highlights a bad coding technique. How much clearer would it have been NOT to use the horror that is ?: ?"

You're kidding, right? You prefer a bunch of if/then/else statements for such a simple assignment? It's far more readable with the ? : pattern - unless you work with a language that doesn't have that pattern - but obviously you don't expect your code to be read by someone who isn't familiar with the language syntax. If/then/else introduces flow control which is always more mentally taxing than a simple binary conditional.

I think the post and the examples were bang-on, personally. I admit I've strayed from this rule once in a while, most often when writing Web Methods (which can't be overloaded), and the names themselves would be excessively long if they described the differences. Then again, those aren't technically comments, they're description attributes.

Aaron G on February 6, 2010 9:51 PM

In my work, the times that I feel comments most lacking is when I don't know how functions are intended to be used, or what the point of them is.

I can read code, and figure out what it does, but I don't know why that library function was added, and without grepping the whole source tree to see *how* it's used, I don't know *why* it's there.

Sometimes, I couldn't care less about how a method actually works, but I just want to know what, as a whole, it does. What is it's one-sentance description? What does it expect as inputs? Outputs? Error codes? Exceptions? And if it's very involved, how about an example? The XML commenting system of .NET is absolutely fantastic, and I find that to be the most important part of a particularly large project with lots of developers -- just document the description, inputs, and outputs of all public methods and it helps everyone get along much nicer.

And if your code is written and refactored into small enough chunks, then one should (in theory) not have any methods that are too painful to sit down and grok should their contents be under-commented but you understand the overall gist of the method.

So I guess I'm suggesting the idea that method header comments are more important than actual implementation-specific comments.

Look at it another way.

If the purpose of a sub is documented with the ins and outs, yet the implementation is undocumented spaghetti code assembler and it's causing a bug, the person fixing the code doesn't need to understand how the old code works -- he can try and learn from it -- sure, but it would probably be easier and cleaner if he just re-wrote it from scratch and didn't try to copy/paste from the old implementation except when it's convenient.

Am I on track in thinking this?

Clint Herron on February 6, 2010 9:51 PM

Couldn't disagree more. As a one-time maintenance programmer, I couldn't care less why code works, I only care why it DOESN'T.

By some strange co-incidence, the lines of code I had to fix never, ever had comments. Code with well-written comments rarely came to my attention, except to suggest where else I should look.

DaveW on February 27, 2011 3:08 PM

"Comments are more Important than Code". This is a verty good Article by Jef Raskin. Writing good comment is difficult. To teach yourself to write comments before you write the code is a discipline. I think the quality goes up if you do this well. The rest for writing no comments is an excuse for not willing to do it. I did not start as a software developer with writing comment. After I read more then 100.000 codelines from others I realized the importance of GOOD comments. You not only write comments for yourself but also for the developers who have to maintain your software.

Herman Van Der Blom on August 2, 2011 1:12 AM

Class, variable, function etc. names should be all the documentation you need for a class. The rest of documentation should be in tests written as a specification of the class.

Comments to me basically say I am unable to give this function a name that appropriately describes what it does, so i will document the intricacies for my future self just in case i forget.

Pete Melbourne on September 13, 2011 4:34 AM

The comments to this entry are closed.