New Early adopter or innovator? InfoQ has been working on some new features for you. Learn more

To Comment or Not to Comment

| by Abel Avram on Mar 03, 2010. Estimated reading time: 4 minutes |

Any developer has written at least one line of comment throughout his code. Some have written many comments in an attempt their code to be more explanatory. This article gathers some of the practices used in writing code comments.

The members of the Seattle Area Alt.Net group have discussed the need and practices for writing code comments. Kelly Leahy prefers self-explanatory written code with very few comments interspersed because he believes comments “only introduce incorrect noise into the system” since they tend to “get left behind in the dust when making code changes”:

[writing comments] it's a personal thing for most people, but I tend to lean very strongly against comments because of their propensity to get left behind in the dust when making code changes - I've seen it happen TOO many times where some comment refers to code that no longer exists, behavior that no longer exists, code that isn't immediately after the comment (because
someone inserted a new line of code between the comments and the original code) or says something that simply isn't true anymore, just because the code got changed and the comment was left alone.

I find those comments to be so much worse than the lack of comments that I abhor comments altogether.

Leahy does not exclude comments entirely and he is using one line of comment for about 10,000 lines of code:

comments can sometimes be useful when you have constraints on design that can't be avoided (performance changes, etc.) that might require a bit more explanation.  I still try very hard to avoid them, and we probably have 1 comment line for every 10000 or more lines of code (except for the silly xmldoc comments, which I personally think are useless noise except in public API work).

Justin Rudd explained that he needed to use many comments in his current project because its API “is so messed up”:

Right now I'm writing a source control package for Visual Studio.  That API is so messed up that I have to comment what I'm doing so I remember why in one place I pass Guid.Empty and in  another (seemingly similar) that I have to pass a particular GUID or it blows up.

I comment which of the 4 solution event interfaces I'm implementing so that the next person that comes along and sees 6 of the 7 methods seemly stubbed out won't delete them.

I comment why I am returning a particular HRESULT out of a method because when I return S_OK - Visual Studio crashes (and it is documented in Connect).

And I comment that even though the docs say you can pass null, you really can't.

In this project, I probably have a 2 to 1 code to comment ratio.

Chris Tavares uses comments for bug fixes:

The comment "// doing this because it fixes bug #####" is not a smell – in fact it's essential.

But Brandon Molina believes it is better to comment bug fixes using the version control system rather than doing it inside the code:

What happens when 10 bug fixes are made?  The code is current and now you have a paragraph of useless information cluttering your code.  Use version control for this.  Where a comment is combined with a diff and the comment actually has useful context.

Brad Wilson added a guiding rule to avoid smelling comments:

"Why" comments == good
"How" comments == suspect

Writing on code comments, Timo Hilden insisted on the need to include good comments:

It’s easy to disregard writing code comments. Let’s face it, we as coders are not going for the Pulitzer prize, so it’s not about the lack of personal ability of being able to express oneself, it’s just plain laziness.

To be honest, leaving code without descriptive comments where they’re needed is much worse than that. Firstly, it indirectly shows the programmer’s lack of respect towards his peers. Everyone knows how frustrating it is to wade through dozens of classes and even more functions with cryptic, non-self-descripting code, especially when the original coder is on vacation, has left the company or otherwise not unavailable for any other reason. A programmer is an artist, with fellow programmers as the audience. And as all artists, we should learn to respect our audience.

Secondly, leaving out comments shows the programmer’s overconfident attitude towards himself. Sure enough, when writing code, we usually have a good idea of what we’re doing. But programming is often about juggling several things in mind at once, and when you next time look at your code, it may be quite difficult to get back to the mindset you were in when writing the code originally. In these quite common situations, it pays to have descriptive comments in place.

Hilden does not support undocumenting – a practice mentioned by Scott Swigart and Jeff Atwood years ago -, considering the following example as excessive commenting:

// Declare category id for products
const int prodCategoryId = 1024;

// Create an iterator over products
vector<Product>::iterator iter = products_.begin();

// Iterate through all products
for ( ; iter != products_.end(); ++iter )
    // Assign categody id to each product
    iter->AssignCategoryId( prodCategoryId );

He suggested combining all the above comments into one explaining the general idea not every step made:

// Assign categody id to each product
const int prodCategoryId = 1024;
vector<Product>::iterator iter = products_.begin();

for ( ; iter != products_.end(); ++iter )
    iter->AssignCategoryId( prodCategoryId );

What practices for writing comments are you using? Are there practices enforced by your company or chosen on your own? Are you supporting the writing-as-few-as-possible-comments policy, believing that the next develop will understand your code, or do you think one should take the time documenting what it is not so obvious?

Rate this Article

Adoption Stage

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Tell us what you think

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread
Community comments

Recommend to read Code complete 2nd. by Wu Junyin

Recommend to read Code complete 2nd.

Recommend to read Code complete 2nd. by Wu Junyin

Recommend to read Code complete 2nd.

Document why, not what or how. by Thiébaut Champenier

There are two types of comments (Java syntax here, but all languages have them):
  • — /** API documentation */

  • — // in-code comments.

Of course API documentation is important, but the comments should only add what’s not obvious from reading method and arguments name and type. Thus proper typing and naming saves on comments.

Code should be self-descripting so that in-code comments should rarely need to describe *what* is done but rather *why* it is done. This part is very important and generally can’t be guessed by readers.

We write code for our fellow human readers, not for the compiler!

Comments can be helpful...if applied judiciously ! by Mohanraj Thirumoorthy

I think, the general feeling towards code comments is that it’s noisy, smelly and something to be avoided. And moreover, the code should be self-descriptive enough that it does not warrant any.

While this sounds good, but it’s far from reality. In my current project, involving multiple developers and changes happening all over, it has definitely increased the level of frustration when someone is trying to fix a bug or change something written by other developers, due to lack of comments and more importantly what the code is supposed to do. We are trying to change the habit, by introducing appropriate comments that explains at a high level of what the code is intend to do, and the effort has been fruitful.

Clean Code by Christopher Bricker

Clean Code by Robert C. Martin has a chapter on comments. Lots of good ideas there.

Create a method with meaningful name by Alex Suvorov

Don't comment a block of code, just move them to another method and give it a good name.

From your example:
void AssignCategoryId(vector<Product> products, int prodCategoryId)

Isn't that better?

No comments, write tests by Tim Linquist

I try to NEVER write comments. As pointed out clean, self-documenting code is ideal. It's easy to write some code, add a comment, and move on without refactoring & rewording your variables/methods/classes/etc. Bug fixes / strange APIs can both be documented with thorough unit tests which often can also explain your state of mind at the time the code was written if you're test driving your code (whole different discussion).

The only time I see comments as being acceptable is to generate documentation as mentioned. Even then, I'd like to run a script that put the doc comments in then pulled them back out after generating documentation.

Avoid comments by Francois Camus

I would also suggest reading the Clean Code bible by Robert C. Martin. Comments should be avoided.

Re: No comments, write tests by Richard L. Burton III

Although Tim's idea is a little extreme, I totally agree that code should be self documenting. If a class is doing more than it's respectable share of work and requires a lot of documentation, something is seriously wrong. Same applies with variables, methods, interfaces, etc.

The same holds true with regards to Unit Tests. Unit Tests should be fairly small in side with very meaningful method names. To achieve this, using setup methods and creating help classes are key.

I strongly believe developers neglect one extremely important thing. Programming is all about modulation and responsibility, regardless of scope. e.g., architecture all the way down to methods.

Richard L. Burton III

Re: Create a method with meaningful name by João Hornburg

I totaly agree!

If you need a comment to explaining a block of code, that block should be a method. Don't name things in comments, name things in method names.

Read Clean Code from Uncle Bob. ;)

It all depends by Jun Ran

I think it depends on the situation of a project, sometimes writting comments can help a lot, for example, those teams with a lot of handovers. And sometimes writting comments will just introduce problems.

Which one will result in a bigger problem in your project? "To Comment" or "Not to comment"? Then make your choose.

Hilden by Niclas Lindgren

// Assign categody id to each product
const int prodCategoryId = 1024;
vector<Product>::iterator iter = products_.begin();

for ( ; iter != products_.end(); ++iter )
iter->AssignCategoryId( prodCategoryId );

I cannot at all understand the reasoning behind giving comments to code like that. And on top of that insinuates that people not commenting code like that do not care for their peers is outright upsetting.

I think such comments are in the way of reading the code. The clutter it, make it more verbose or worse inconsistent. There is absolutely never any reason to double state anything, number one rule of programming is to remove duplication.

People writing code in the way do not care for their peers, if they did, they would refactor instead of commenting smells adding more smell. "Alex Suvorov" already mentioned what to do, it is far superior, it lends it self to proper refactoring and removes duplicates and states intent and removes smells all in one go.

Part from that the code in itself seems to be wrong, products are included in a category not assigned a category, .i.e, category.AddProducts(products). There seems to be a mismatch between DBMS and Object Oriented representation. That might actually be worth explaining why, but it depends on the domain.

It is funny enough he managed a spelling error in the comments just adding to more smell.

Tests describe what, code describe how, requirements describe why.

Ideally tests contain both what and why, which is BDD.

Given that, code show almost never contains comments about how. Rarely things about what and why. Only when you for obscure reason choose to deviate from what and why in the tests/requirement or when how cannot be simplified enough to state intent in the prose of the language., or when you outright skip to implement something, or when it is untrivial to understand how to extend something for people arriving to the code.

The reason people want comments is not to describe what the code does per say, and particularly not to explain that the next statement is really a for loop just in case you didn't understand it on the keyword for...They don't want to know what the code does for the heck of it, actually the less time than have to spend on that the better, they want to know how to extend it so it does something more while preserving functionality of the old. Open for extension closed for modification comes to mind...

AssignCategoryId for instance is not such a good name, if you call it with 2 different ids, does it belong to both categories? the first? the last?

SetCategoryId or AddCategoryId are much better names even if you have unitTests named like "ProductTest::canOnlyBelongToOneCategory", "ProductTest::lastSetCategoryApplies"

About extension, what if AssignCategoryId = SetCategoryId, how do you extend your system so that products can belong to multiple categories? If it is not part of your requirements, why did you do the limitation here for no apparent reason or cost/time saving?

It seems highly unlikely that such business logic should be part of what looks like domain objects, even less hard coded, but if it is hardcoded it should be through a good name such as product.SetCategoryId()

Those are my cents, I like comments when they are due, but I would rather have less comments than too many, you might not the forest for all the trees. Comments are smells and just because they are not code does not mean that get a free pass to exist where they shouldn't.


comments for bug fixes by Guo Ford

it fixes bug ##### comments should be put in the vcs(svn,cvs) commit message.

Questions for developers by Bruce Rennie

An interesting question for developers:

1. How might your coding style/practices change if you worked with a language that did not include comments?

2. Are the changes that fall out of #1 above (if any) worthwhile even if a language does provide comments?

For me, comments are waste. Ideally, developers should be able to understand all code without the use of comments. Any comment represents a failure to achieve that ideal and is therefore, by definition, evil.

Now, that doesn't mean I never add comments to code. Sometimes reality trumps ideals, especially with legacy code. But I still view all comments as a failure and continually work to render them unnecessary.

Code Comments by Pete Haidinyak

I have one suggestion to the 90+% of those who don't comment their code or think one comment per 10,000 lines of code is enough. Please add a header to your classes that states...

To Whomever is maintaining this code. If you don't understand what I have written or are confused by my coding style please feel free to call me anytime day or night at (XXX) XXX-XXXX and I will explain to you whatever was going through my mind whenever I wrote this.

Just as comments can be out of date, self-documenting code can be out of date and just as confusing.

Re: Code Comments by James Brechtel


Why? Do you think the person who lets self-documenting code get out of date (method names and variables become misleading) is EVER going to update documentation to make it up-to-date ?

I think your logic is flawed.

Re: Code Comments by Bruce Rennie

So the answer is to add obsolete comments to obsolete code? Not sure if I see the improvement.

Re: Code Comments by Pete Haidinyak

Again, if you don't have the discipline to comment your code, add contact information. Seems simple enough. And frankly, to cater to the lowest common denominator, the coder who hacks their way through it, is not the way to produce a quality maintainable code base. I think everybody should spend six months doing nothing but maintaining somebodys elses code.

automatic generated comment about comments by Stefan Wagner

Most comments I read are plain lies like:

// generated method block

and consequences of 2 or 4-blank-indentations like

} // end if
} // end while

Re: automatic generated comment about comments by Pete Haidinyak

If the block is long enough I will add

} // - End if p_status was null.

} // - End while there is still data in the queue.

This is a quick way to make sure you are at the right indentation level.

Re: automatic generated comment about comments by Ryan Eccles

Although I agree with the code should be as self documenting as possible it isn't always practical or possible. I can't run through our system-willy nilly changing method signatures or I would certainly be fired. Our system has been developed for over 10 years, it has a lot of baggage with it. Comments are an absolute (and unfortunate) necessity when API changes can't happen. Comments present a reasonable way of communicating via the code when the code can't change.

Also in my work I deal with a lot of tuning and optimization. It's not always evident why something is done the way it is. A comment can be invaluable the more obtuse the optimization (i.e., using this memory approach to avoid excessive young gen GC'ing).

Sure new code can have these strict THOU SHALL NOT COMMENT rules. I've come across comments that are out of date but I've also seen very very very helpful comments. I usually correct the aberrations when I find them and appreciate the forethought of the other developer when they are good. I don't buy this either-or nonsense as a general rule to coding; it sounds like snake oil.

It seems the opinions here can be cleanly divided into two types of people based on the argument. The no comment crowd is very concerned with how it negatively affects them, the pro comment crowd is concerned about how it positively affects others.

My opinions are of course shaped by the experiences I've had working with others and the projects I've seen. I'm wondering if people could include some historical context with your opinion, are you a small twenty person shop or a larger thousand+ person shop. Have you always worked in a small/big company? Did you start young, or learned in college? How long have you been writing code? How big are the projects you have worked on? Also, if you are of either persuasion could you address both sides? I'm interesting in seeing your responses, I'm wondering how these factors affect your opinion.

Re: Code Comments by Mark N

Pete, it has nothing to do with discipline, unless of course, one is not using ANYTHING to comment their code.

Adding comments to code is only part of producing maintainable code. Using "self-documenting" or "self-commenting" code goes much further.

Re: automatic generated comment about comments by Mark N

1. Do you use an IDE?
2. Do you keep your blocks small?

If not, this explains why you need comments. If you have to add ending brace comments, then you you have too many indentations and/or too long of blocks of code.

As a side note, I had do maintain a COBOL program that had such a long method, the developer used "comments" as "mile markers". It took me a bit to figure out what he was doing because they actually are GoTo tags and I could not find anything that used them.

Commenting on intent by Todd Farrell

Like most things, there are usually *extremes* at either end of the spectrum. Contrast the popular big design upfront approach with an organic, test-driven design that evolves only as necessary. My thoughts are that most people do not sit at one extreme of the spectrum, but actually fall somewhere in between -- usually favouring one paradigm over the other.

With regard to comments, I often write concise statements of intent at the method-level in unit tests and non-trivial public methods before implementing them. Where practical, I try to give methods readable names that convey intent as much as possible, but well-formed English is most effective to convey meaning than programming language identifiers will ever be ;-)

Comments of any kind can be neglected of due maintenance... that's why I write (or change) them first!

Re: Code Comments by Luis Espinal

Pete, it has nothing to do with discipline, unless of course, one is not using ANYTHING to comment their code.

Adding comments to code is only part of producing maintainable code. Using "self-documenting" or "self-commenting" code goes much further.

The problem with this is that "self-documenting" code excels at that, at documenting itself. It it is limiting in the way they could document business reasons, integration points to other systems and edge cases (and changes to these two over time) which drives coders to write the code the way it is. The amount of information that can be conveyed with self-documented code is invariably less than the information of a system as a whole : pigeonhole problem thingie.

Self-documented code, well structured, with data and control logic aligned and good choice of method and variable names is certainly a must. And it should (will) be accompanied with comments on the nature of things that cannot be reasonably captured with self-documented code at all.

Re: automatic generated comment about comments by Pete Haidinyak

Yes I use an IDE (IntelliJ) and I try to keep my block as small as possible. I'm not one of those programmers who will artificially add a method call just to keep the calling method within a certain size limitation. Sometime a method can be complex and parts will run off the screen (even on my 30" monitor), and I have found the ending brace comments a quick way to see where I am at without using the IDE to highlight the top. Also the next guy who has to look at my code might have a 15" monitor with the IDE so cluttered as to only show 5 lines of the method.

Re: Code Comments by Mark N

Self-documented code, well structured, with data and control logic aligned and good choice of method and variable names is certainly a must. And it should (will) be accompanied with comments on the nature of things that cannot be reasonably captured with self-documented code at all.

Re: automatic generated comment about comments by João Hornburg

Do you have blank lines inside your methods? Why?

Wouldn't it be much better to extract a method from every litle code block inside your method? This would produce a much higher-level description to what your code is doing.

Some pieces of Code Complete, courtesy of InformIT by Cory Wheeler

Several others have mentioned this book. Here is a link where you can find some transcripts from the book, several of which relate to code comments.

Re: Some pieces of Code Complete, courtesy of InformIT by Cory Wheeler

Sorry for the error... Meant to reference the Clean Code book by Uncle Bob in the subject.

Re: Code Comment by Leyu Sisay

When ever you want to write a comment stop and think whether you can refactor the code to describe it's intent well.

The following books address the main subject and how to write clean & self documenting code:

  • Clean Code

  • Refactoring: Improving the Design of Existing Code

  • Code Complete 2

Re: Code Comments by Binoj Antony

Self-documented code, well structured, with data and control logic aligned and good choice of method and variable names is certainly a must. And it should (will) be accompanied with comments on the nature of things that cannot be reasonably captured with self-documented code at all.

Documentation tools by David Poole

Products like Innovasys DocumentX and JavaDoc grab specifically structured code comments in order to produce a help file or web based help.

If we all coded to a consistent high standard then there would be no need for comments but life just isn't like that. Some awful abberations slip through the net and end up in places where they are difficult to get rid of.

I would say keep your code clean enough so it shouldn't need commenting (other than API comments to be picked up by documentation systems).

Because comments don't compile it is easy for developers to ignore existing comments when making code changes. You can either take the view that there should be no comments, in which case you should remove them as you come across them, or you can make it part of your discipline to make sure they are applicable.

Modifying Old Code by Phil Runciman

I try to break up the code into units of thought. These are commented. Generally I can then start to see patterns and get down to what was intended.

In these cases if the unit of thought changes then change the code too. I write comments for the poor sucker who follows after me. Generally that person is a new delta of myself!!

C.A.R. Hoare, Professor of Computing, Oxford said, "The readability of programs is immeasurably more important than their writeability." I agree. Comments help where the program language fails.

One COBOL program from an ERP system was so bad that I still have the listing... just-in-case! It was an order entry program and took two weeks to fathom. It was really gross code.

I also put comments in saying things like "modify in XXX not here". These are very useful reminders if there is a structure into which the code has to fit. Twice today I benefitted from such a comment.

Try assembler programming without comments.

I believe good naming habits are even more valuable but that is another story.

Nice, but... by Guy Pardon

Writing good comments is hard, but writing self-documenting code is light-years much harder. DDD is a good start.

Besides that, writing test-driven test specs to replace documentation is equally hard.

I recommend the following:

-use Javadoc to document pre/post conditions and exceptions
-write comments to WHY you are doing things
-do code reviews for the rest


Re: Nice, but... by Henri Gerrits

I mostly agree. I only use comments in the following situations, where things are not obvious from the code:

- workarounds for bugs in someone else's API
- assumptions about someone else's badly documented API
- optimization shortcuts (also briefly explain why optimization was necessary in the first place)
- complex algorithms
- thread (un)safety (though annotations can go a long way)
- preconditions that are too difficult or impractical to test with assertions

These are all necessary for the next person to understand what I did or why I did it, before making changes.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

36 Discuss

Login to InfoQ to interact with what matters most to you.

Recover your password...


Follow your favorite topics and editors

Quick overview of most important highlights in the industry and on the site.


More signal, less noise

Build your own feed by choosing topics you want to read about and editors you want to hear from.


Stay up-to-date with curated articles from top InfoQ editors

"You dont know what you dont know" change that by browsing what our editors pick for you.