Tuesday, January 11, 2011

Don't Waste Your Time Commenting Source Code

I recently had an argument with a colleague about source code comments. He called it one of software development best practices and suggested that any programmer worth his salt writes extensive comments. You hear this pretty often from people who consider themselves "old school". Well, I have been writing code since early 90s, but I strongly believe that 90% of source code comments are a waste of time. Let's review the arguments...
Pro: Comments explain what the program does, so the person maintaining the code can understand it easily.
Well, it sounds good on the surface, but if you think about it, a well-designed program doesn't need comments to be maintainable. A well-designed program uses classes and design patterns; it has high cohesion, low coupling, and limited cyclomatic complexity. The names of classes and variables are carefully chosen to be self-explanatory. We know that programmers don't generally have unlimited time for development. If the choice is between a well-designed program without comments and a thoroughly commented but poorly architected one, I will choose the former any day of the week. Frankly, I would rather have developers spend time polishing their design skills than technical writing skills.
Contra: Automated unit tests explain what the program does just as well, and they never become obsolete.
The truth about source code comments, and any written documentation for that matter, is that it quickly becomes obsolete. Take a look at this real-life example I took from StackOverflow discussion:

/**
 * Always returns true.
 */
public boolean isAvailable() {
    return false;
}

There is no guarantee that the person changing the code will take time to update the comment. There is nothing your integration server can do to enforce this. On the other hand, consider this unit test:

var result = myobject.isAvailable();
Assert.IsTrue(result);
As soon as someone changes the method to return "false" instead of "true" and checks the code in, the unit test will break on next build, and pretty soon the developer will be looking into the issue.
Contra: What makes you think people can write clearly?
Let's face it, not every programmer can write well in English (that goes without saying for us immigrants, but I have seen comments written by native English speakers that were profoundly confusing). On the other hand, unit tests are written in programming languages, so developers can apply their core competencies. Natural language comments can be ambiguous, vague, sarcastic, or humorous. Some may be even fun to read (that StackOverflow discussion has some real gems!), but unit tests are much more practical - they leave no room for different interpretations.
Pro: Sometimes you just need to leave a note...
This is the only case that I would concede. Here is an example to illustrate this point:

// 
// Dear maintainer:
// 
// Once you are done trying to 'optimize' this routine,
// and have realized what a terrible mistake that was,
// please increment the following counter as a warning
// to the next guy:
// 
// total_hours_wasted_here = 39
// 

55 comments:

Anonymous said...

Oh, this is classic, doc! ha ha.

So a few months ago while converting the PHX platform from 3 to 4 I found a comment:

// RM 6-22-2007 Temporary workaround

Ha ha, it's still there. I will go revise it today to:

// RM 6-22-2007 Temporary workaround
// SB 1-13-2011 Permanent workaround


Shawn ;->>

RM said...

Nice catch, Shawn! Kind of reminds me president Bush's tax cut :)

Unknown said...

Well put. I do hate code without comments sometimes. But come to think of, it is the code that I hate. Comments would not have made it any better.

RM said...

@Anthony: Exactly - you can put lipstick on the pig, but it's still a pig...

Anonymous said...

If people are bad at something, it's generally advisable to help them improve, not abandon that something altogether.

Why not teach good commenting (a proven technique) rather than pushing "high cohesion", "loose coupling", etc., which in my experience are useless unless you have a buzzword quota to meet.

Fekri Kassem said...

Comments distract me from reading code

hacksoncode said...

Comments that tell you what the code does are worse than useless. Write the code to be clear.

Comments that explain *why* the code what what it does, however, are priceless, and are utterly unreplacable with unit tests (unless those are well commented, I suppose :-).

Anonymous said...

This is the most retarded article I've ever read. Yeah, let's NOT comment anything so when we revisit it in a few years, we have no idea what is going on - or even worse, YOU quit and the new guy doesn't know what's going on.

I can tell that you are NOT a professional programmer in the slightest - you are just a "Dabbler" - in which case, you don't have any credibility when it comes to giving out tips.

Kiaran said...

I find that I relied heavily on both reading and writing comments when I was learning to program.

But as you gain fluency with a language, comments increasingly feel like superfluous clutter in the best case, and misleading trickery at their worst.

Anonymous said...

Typical programming advise from an architect who thinks he is an awesome coder. Any good coder worth the salt knows how important commenting is.

Queen Frostine said...

Riyad.. when is the last time you read actual source code?

Anonymous said...

Having worked in the industry for 12 years as a software developer, including helping develop software using one of the largest codebases in the wild, with legacy code often going back to the early 90s, I find this article ludicrous. Any absolutist philosophy should be carefully examined, and this is no exception.

Henry said...

Examples you shown in the blog are stupid and do not reflect a real life examples on how comments in the code could help.

Mostly the comment should explain why the code is there rather than whats it for.

Write a complex code and let me quiz you what the code does in few years from now. Not sure if you ever contribute to open source projects.

Unknown said...

In a form of protest I am currently using JAutoDoc to generate such gems as this:
/**
* Gets the name.
* @return the name
*/
public String getName() {
return name;
}

The old practice of 10 or so line methods helps a lot with readable code. When the method gets too long break it out clearly and it will self document, if you don't know why a method is named a certain way rename it. That and unit tests.

Unknown said...

Code is not self documenting. This example about isAvailable() would have been more useful if it told the reader what it means to be available.

Is it available because no one else is using it? Maybe it's available because you met a minimum criteria that allows it to be available. Don't tell the reader that it returns a Boolean -- tell them *why* it returns a Boolean....

This doesn't obviate the need for test driven development, my best code has both test cases and comments.

Anonymous said...

What you're saying is a joke. You present bad coding examples to show the stance of code and then say how dumb it is to comment THAT line of code. That's a logical fallacy known as a straw man argument.

Imagine if you see code like this:

for (Stock stock : stocks) {
stock.clearBuffer();
futures.add(stock);
}


.. Now you might think: WHY does he clear the buffer?! Now look at this code:


for (Stock stock : stocks) {
//NOTE: there's a bug in the futures API that
//assumes a clear buffer for it to work
stock.clearBuffer();
futures.add(stock);
}


....

That's just ONE of HUNDREDS of reasons WHY you should comment some code.

Your straw man argument only works if you have a system you're building from scratch.

Unknown said...

Comments also help new coders understand how to support or modify your code.

For obvious patterns, verbose comments are a waste of time. However, what is 'clearly written' to one coder may be obtuse and convoluted to another; hence, software being rewritten every time someone new takes it over.

Or, that day you're out sick and someone needs to make a quick addition -- not a bug fix, because of course your code handles all corner cases without flaw -- and in making that addition fails to recognize your cleverly nested class structure and causes a stupid crash.

Please: comment responsibly.

alan said...

Woah. You sound exactly like an Information Systems graduate; "We need *buzzword* and to synergize *buzzword*". Don't pretend like you've ever inherited a large codebase, it's quite clear from this article that you haven't.

Numberwhun said...

Sure, I can see what you are saying with regards to some languages (like C for instance), where writing good code makes it easy to follow.

Where I don't agree is with languages like Perl, which allow for obfuscation. Supporting some really obscure Perl code will make any coder scream if there are no comments to explain what a piece of code does.

I don'g think that every single thing needs commenting because, as you said, there is such a thing as too much and it would get in the way. But, well placed comments for code that needs it is not a problem.

I am one of those that only comments if I find its needed. Don't see that as a waste of time, even with my well written code.

Christopher Martin said...

People complain that I don't comment enough, so sometimes I sit down and start documenting classes. But whenever I need to write more than a sentence to explain something, I find that it's easier just to refactor the code to be more intuitive - So I still don't end up writing the comment.

Unknown said...

If you are doing any sort of physics calculation ... say a 3d vector field moving over time. And you are integrating over that field w.r.t. some variable.

You *will* have a lot of matrix stuff going on with pointer arithmetic.

You *will* appreciate the fact that you dropped yourself (or your successor) a few lines of commentary about this code.

Coding isn't rocket science, clearly. But crafting efficient code to solve real-world problems that aren't layed out as stack/frame pointers means that there will be some abstraction going on. That abstraction deserves to be documented.

I dare you to get 20M lines into an embedded system and remember the code that you even wrote yourself 3 years ago.

Dude. Your examples are mis-leading (Always return True? Why have a sub?) -- and your case is wrong. Come back when you have slung a few million more lines.

Mihai said...

NO. Comments are very necessary. Everything someone says comments are superfluous, a file (> 500 lines) gets created somewhere without ANY comments. Try fiddling with a specific feature of a project new to you, if it takes a couple hours just to find where in the 10000 lines of code it is!

Case in point: Every file and nearly every function should have a comment specifying its role! Nearly every time I write code, it seems obvious to me. As an outsider, and without comments, will the same code be obvious to you?

Anonymous said...

My system is simple. I look at a routine I've written and ask myself: "Will I remember what this means next year"?

If the answer is "no", it gets comments. If the answer is "yes", then it gets minimal or no comments.

pelrun said...

It's not all or nothing. Comments aren't going to save awful code, no matter how extensive they are. Clean, self-documenting code can get away without comments for the most part; you then use comments where they're most needed - for those code sections that need the extra semantic information.

Anonymous said...

I think the tenor of the replies have it about right.

1. Comment unexpected API, Compiler, Language behaviour and workarounds. Internal stuff that is not obvious.

2. Comment the 'why' more than the 'how'. External stuff - that is almost never obvious from sola code.

It frustrates me how many programmers have their head stuck in the language. If they applied that to real life, they would learn the intricacies of, say, French, and never have a conversation. They'll explain how the ablative case is declined in the past tense of an irregular verb, but never talk to anyone.


A comment like this:

// Sales Tax does not apply to ladies handbags in the case of fire-damaged articles in Ottawa

or

// Sales Director wishes to start a discount by volume system in the future, therefore this variable is included as a hook point, and can be set in the derp.ini file

These are valuable comments.

Anonymous said...

I just finished updating a WIN16 program I wrote in 1991. Without the comments I wrote then I would have been doomed. BTW the only reason I had to rewrite it was that it wouldn’t run on a clients Win XP-64 setup. The program originally took 6 months to write, it took less than 4 days to update it. I am actually amazed that the program was good enough to last that long and how good I was at 20-something. I was a bit too clever in places (single dlg proc for about 6 different dialogs) but otherwise it wasn’t too bad. Without the comments it would have been incomprehensible as I had forgotten how the core complicated algorithm worked. I also think that well commented code is much more readable than bare code. I don’t comment the bleedin' obvious, only the stuff that I know I will forget.

George said...

I completely agree that comments that say what the code does are useless, and should be avoided. But you've missed the point of comments completely. There are two very useful things you can do with comments that you can't do in code:

- You can explain *why* the code does what it does. In other words, you can explain design decisions that led you to write the code the way you did, and you can summarize the context in which the code will operate. For example, perhaps you wrote some code that only works if its input is sorted; you should point that out, and explain why it's safe to make that assumption.

- Very importantly, you can explain what the code *doesn't* do. This is something that's very hard to articulate with tests! Many times, I find I've come up with three or so different approaches to a problem. A reader of my code might wonder "Why hasn't this been done the obvious way?" A brief comment can save a huge amount of time in those cases.

James said...

Or better yet.

for(int i =0;i<100;i++) { //Start of for loop

Sargo Darya said...

Seriously there's a reason why commenting exists. Sometimes you need comments to explain what is going on because your client wanted to have major changes which do not fit in the overall structure of the current application so the next one maintaining the code will have major issues understanding what the hell is actually going on.

Commenting is also very reasonable if you want to design an API which other developers have to use. They have to rely on the Documentation generated from the comments.

If you are absolutely sure that you're the only one who works on a project you may choose not to write comments although I'd still do it. You never know if you look back at the code in a few years and it will take you more time to figure it out again what you've done instead of reading a comment explaining what the method does.

TL;DR: Disregard OPs post and write descriptive comments with return types etc. and anytime you think something COULD be unclear.

Lex van der Sluijs said...

Comments should not be necessary to explain WHAT a program does, but I really do appreciate comments when they explain WHY it is done that way, when this is necessary!

Shahal Tharique said...

I agree with the design patterns, coupling, cohesion and other stuffs you said. Those are useful when it comes to design in general ie, we are not talking for a particular language. But comments speaks particularly for the language.

I strongly disagree from ur statement 'Its a waste of time'. I am sure there are a millions out there who agrees with u, but that would be just because they are lazy(and selfish) programmers. In fact, if u get a code from a source repository(try the vlc code), it's pretty hectic to read and understand, just by the code.

I'd be real glad if you dont misguide ur readers.

Anonymous said...

I disagree strongly. In 3 million lines program I work with daily I really wish people would have commented more. Mind you now comment the code, per say, I agree that I often a waste. But comment/document the interface. Not explaining how a class does something but what it exists in the first place, its purpose and how you use it.

Your suggestion about not commenting amounts to releasing say Qt (from Trolltech) without any documentation of the API, but instead give is a crapload of unittests.

Personally I don't document every function but I try at least documenting each class, and sometimes write code examples explaining how to use it. Sometimes it might be necessary to document how you would subclass an abstract class.

Other times you have complicated code based on a paper. You really want to write in the document what are the equations you are using, what paper was the method published in, so you can get the paper while reading the code. Otherwise it is next to impossible to understand the code.

Anonymous said...

Horrendously wrong conclusion about comments in coding. I would hate to have to maintain anything you have ever writing. Aside from the reasons others have posted here, comments, even if wrong, communicate the programmer's INTENT. This can be vital information regardless whether or not the code works.

Peter said...

Comments are not bad, but comment that tells you what the codes does is a waste of time. Documentation that say what role a given piece of code (object most likely) have helps. This can be achieved with a proper UML diagram as well, so it all depends on where you document your code.

I'd much rather that people comment on WHY they have used the solution you're about to see. What specific problems prevented them from using the obvious, ect. it makes it easier to understand the code in the future.

Unknown said...

I've heard this for the past thirty years. Good, well written code is always enhanced with good, well written comments. Many programmers seem to have the idea that they can be objective about the quality of their code.

Anonymous said...

Unit tests do not describe what a program does. They describe how it should function.

Dave Humphrey said...

Yes, exactly. I've written something similar in the past: http://vocamus.net/dave/?p=894.

Dave

Tha' Freakin' Pope said...

IMO, the case Riyad's missing is when a poorly-skilled developer is the only person available who can maintain the elegantly-written code. The better the code is written, the harder it can actually be for the developer to understand. For instance, yesterday I (I'm the poorly-skilled one) had to maintain a Linq statement. I don't really know Linq that well. I tried to fix it by tearing it apart and using foreach loops. When I asked the busy, original developer for a quick code review, they were less than pleased. They stopped what they should have been working on, attempted to write an even more complex Linq statement to perform the same effect as my maintenance hack. After an hour of trying, failing, and being unable to debug an odd error caused by the enhanced Linq statement, they wrote a simplified version. However, this simplified version didn't fully address the maintenance request. So, I hacked that statement again, with a foreach loop. I've yet to show it to the original developer. We'll see how that goes. Anyway, in this case, the comments might not have helped. However, I've been struggling to understand the code written by our more skilled developers and there are several places where a hint would have saved me a bunch of time. Some of you might say there's no substitute for experience. I agree, but experience is not always available or feasible, and the work must go on.

Scott S McCoy said...

I tire of this argument, it's bogus.

"People don't write good comments, so let's quit writing comments altogether". Si not unlike saying "People don't write good unit tests, so let's quit writing unit tests altogether" which is really *quite* like saying "People don't write good software, so let's quit writing software altogether" which is a very defeatist approach and contrary to the whole point of what a great many of us would like to see done. The idea that software and unit tests will be self-documenting is plain-ass silly.

I am especially annoyed with an example here being Javadoc, which is to say, comments are analogous to documentation and we should quit writing documentation. Let me see you go lose on the JDK, or Spring Framework, or Restlet, or any other sizable API without knowing a lick about what the thing is even *intended for* and let's see how you fair with no documentation. But here's the 15000 unit tests you probably can't even figure out how to run without a README, have fun.

In fact, if you want to test this theory that code and unit tests are superior to documentation, next time you have a friend who wants to learning Java why don't you send them a copy of OpenJDK with all the documentation and commentary removed, and the TCK with all the documentation and commentary removed. Yes this will work well. Rinse and repeat for other programming language SDKs and try and honestly convince me that `help()` hasn't been useful to your learning python or perldoc for your perl and so on...

No documentation, no comments, sure, these are brilliant ideas, if you're writing simple simple programs which do every obvious things, and that's all you ever have to concern yourself with. But having been doing this since the 90's myself, I find I have to read *my own* documentation rather often and not because my APIs aren't clear enough, but because damn-it, there are a hell of a lot of them to deal with and I even forget which ones exist half the time.

Rather than writing no documentation and commentary because the quality of your documentation and commentary are low, why don't you focus on increasing the quality of your work? That is, put in place a code-review process or something.

Merennulli said...

The "old school" programmer is right...for old languages. When you had 8 characters to name your function, you needed a comment to explain that FYBALADJ had nothing to do with adjusting the fiscal year balance, but instead was to move a ASCII-art of balloons on the fiscal year reporting software's completion screen in DOS.

Like anything else, the game changed, but people clung to what worked before and still worked, rather than looking at what worked better.

Keeping it "old school" is great if you're dealing with fashion or art where you have a target audience that is resistant to change and likes that. Anywhere else it's code for refusing to learn.

Pedro Assunção said...

I think comments are useful, regardless of how neat your code is. Except for self explanatory code, a human will always understand it better if it's explained in simple words. Of course it takes common sense to apply this method and - as we all know - most of the times it's not common ;)

Archi said...

2 chapter names from the great book "The Pragmatic Programmer: From Journeyman to Master":
1) Build Documentation In, Don’t Bolt It On.
Explains why docs (comments actually) must be in the code and why you need tools like doxygen.
2) English is Just a Programming Language.

Joe said...

I can tell you are not a professional software engineer. Once you start writing code for an industry you realize how important documentation is. When there are numerous people working on the same software that may consist of thousands of lines of code it's extremely important to properly document software. Not all code is object oriented either and easy to read. Diagnosing legacy C code isn't always so simple. Not to mention all the embedded software and controls software. Yea lets not document mission critical software...good idea.

You seem to have written a few Java programs and came to this conclusion.

ben.biddington said...

Totally agree: if it needs comments, it needs redesign.

Dave Newton said...

To those saying this is "retarded" or "must not have ever written any real code": seriously?

I can come up with *hundreds* of examples of similarly useless, poorly-maintained, and sometimes dangerously misleading inline documentation.

If you read a comment do you *really* trust the comment to be correct? If you do, *you're* the one that's never worked with *real* code.

The code always wins. Code is the only artifact that is guaranteed to be accurate, because it's what runs.

Some in-line documentation is priceless. But code *must* communicate as much information as possible to its readers. Good code *is* documentation. Code should be a story. Comments are the backstory.

Anonymous said...

You're wrong. There is no single end-all solution. Especially if you aren't working in a vacuum. Proper design, comments and testing are all important to QUALITY software that is maintainable. Comments and tests must be maintained. And a GOOD developer will do that.

Seth said...

I personally fall victim to CYA code comments:

// This is a nasty hack and should be
// killed with fire if our properties
// files are ever organized in a sane
// fashion.

They make me feel better. I hope they amuse others rather than generate eye rolls.

Jeff said...

I'm totally with you!

http://www.barebonescoder.com/2011/01/comments-are-always-failures/

Tom Dalling said...

I wrote an article similar to this a while ago, and it got the same reaction on reddit.com/r/programming. Around 1/5 agreed, another 1/5 had thoughtful criticism, and the remaining 3/5 had a big cry with insults and whingeing. Such is reddit, unfortunately.

You're right in that a lot of comments are crappy, and crappy comments are unnecessary and even harmful. However, like me, you took it too far and claimed that all comments are bad, which I don't think is true.

The truth lies in the gray area between your view in the article and the childish tantrums in the comments.

Ramesh said...

It is not mandatory to write comments in code similar to the convention of coding to be maintained.
Comments on the code is a form of documentation.Is it always the case that same person handles the project?Is it always possible for us to maintain number of document files separately telling this method has been added for the enhancement?
Comments updating is equally important during code updates.

I think writing of standard code with design patterns and conventions is equally important as the relevant comments to be written within the code.

Ryan Lund said...

I have to agree with this to be honest. Well written code is clearly understandable to anyone working on the project and those who dont understand well written code are usually not experienced enough to be working on that particular project anyway. Also, taking comments out of the code makes any future developers think a little harder about why things were written that way in the first place forcing them to develop a deeper understanding of the system, and potentially teaching them new tips, tricks and methods they wouldn't normally attempt to understand if the comments simply explained the final outcome. However, i am a one man team so the need for commenting isn't so great most of the time.

Anonymous said...

People who are advocates for commenting code are the same folks who spend all of their time ingesting the nuances of things like Scrum and XP Programming, with the delusion that it will produce "better" code.

Spend your time writing good code and learning how to write good code, and you will produce good code.

All these little practices and processes dont produce quality, and spending your time trying to improve quality through these mostly useless processes, do not improve your quality.

As a developer, if you dont understand the code that you are reading, and rely on the comments to help you understand it, there is a much larger problem.

Anonymous said...

I posted a response (semi-humorous): http://glassocean.net/riyad-mammadov-enterprise-architect-says-dont-waste-your-time-commenting-source-code/

Danny Tuppeny said...

I couldn't disagree with this post more. I spent the huge majority of my time stepping through someone elses code trying to understand what it does.

Not writing code comments because some people write crap comments is like not writing code because some people write crap code.

I posted my opinions on my blog:

http://blog.dantup.com/2011/03/writing-comments-in-code-is-not-a-waste-of-time

Anonymous said...

Anyone who disagrees with this post (sincerely) isn't a real programmer. A few notes to highlight something unusual in the code is the maximum that should be used. Beautiful compact code is *always* easier to understand and maintain than a verbose bloated inaccurate mess. If you *need* comments, please change careers, because your uselessness is dragging down the whole profession.