Code Focused

To Comment or Not to Comment

On VB columnist Joe Kunk explores the benefits and drawbacks of commenting source code, and finds that the answer is not as clear cut as many might think.

More on code commenting:

To badly paraphrase Shakespeare's Hamlet, "To Comment or Not to Comment, that is the question". There is a surprising amount of passionate debate within the developer community regarding the usefulness or desirability of comments in production source code. Should source code include significant comments or none at all or something in-between? In this article I examine the comments debate from a language-independent viewpoint. No matter what your favorite development language, the role of source code comments is something you should carefully consider.

In the following discussion, comments are defined as those lines of text added to the source code following a specific language token to indicate non-functional text, explicitly ignored by the compiler or interpreter. Forms of comments that are meant to provide some meaning such as compiler directives or metadata are outside the scope of this article.

Everyone Carefully Comments Their Code, Right?
At first glance, it seems so simple. Developers should comment their source code so that the code's intent is clear to the next developer or even to the same developer at a later date. Most professional developers have experienced pulling up their own source code months later and felt the surprise of seeing strangely unfamiliar code and asking themselves the question, "Why did I do that?"

As computer science students, we were graded on the quality of our comments almost as much as the correctness of our code. High quality comments were the sign of a professional developer and comment free code was evidence of a rank amateur or someone who had spent too many hours at the bar the night before. Comments were among the universal truths of software development, as critical as proper requirements definition and effective testing.

Imagine my shock when Paul Kimmel, author of multiple computer books and a long-time technology columnist, told me that he rarely if ever comments his source code. His stated approach is to write only very small, well-named methods that are so self-evident in their purpose that comments are unnecessary in his opinion. Since then I have heard statements like "Comments are evil," "No good comment goes unpunished," and similar disparaging remarks.

Let me try to distill the debate to three pro-comment and three anti-comment points:

Pro-Comment Point #1: It's important to communicate what the code SHOULD be doing
Source code must follow the syntactic tenants of the computer language. While language designers make significant efforts to define a readable syntax, at its core the language syntax exists for the compiler or interpreter and not the developer. Thus, comments are required to communicate the intent of the source apart from its functionality. When reading source code, it is extremely difficult to be absolutely certain of what the code is doing, as well to be certain as to what the original author intended. Comments should clearly communicate the developer's intent and if needed, an explanation as to how the source code algorithm accomplishes that intent.

Pro-Comment Point #2: Comments show respect for the next developer to read your code
The Golden Rule applies in source code as well; do unto the next developer as you would have them do unto you. Source code should be written in the way that you yourself would most like to encounter unfamiliar code. It should be well-structured with a clear logic flow, and be both efficient and effective. Comments enhance the readability of the code, so that its intent and approach are immediately apparent with a clean appearance.

Pro-Comment Point #3: Comments indicate potential problem areas to avoid
Comments should mention factors that may be of concern for the developer or tester. Boundary conditions, valid argument ranges, and corner cases are all important factors to mention in comments for the benefit of future developers and testers.

Anti-Comment Point #1: Comments take time and have cost but do not influence runtime behavior
It is true that comments have zero impact on the output of the compiler. Eliminating all comment lines is one of the very first steps performed by the compiler or interpreter. Clearly the existence of comments is solely for the benefit of the reader. The creation and maintenance of comments carries a cost, and that cost is justified only if it provides a benefit greater than that cost. The presumed benefit is easier maintenance in the future, but that maintenance can be just as easy with comment-free well-crafted source code.

Anti-Comment Point #2: Comments are not properly maintained
Since comments have no impact on the runtime results, they are sometimes neglected when the source code is updated. Source code maintenance as a result of a production bug is often done under time pressure and maintaining comments is seen as an unnecessary delay. There may not be any particular standard for maintenance of comments in production source code and it is left to the discretion of the individual developer.

Anti-Comment Point #3: Comments may be unrelated or offensive
Comments are just that: comments. And sometimes those comments reflect the developer's frustration with the code in ways that, well, should not be repeated in polite company. Sometimes comments are written by developers that misunderstand the code and reinforce that misunderstanding through incorrect or misleading text. The feeling is that bad comments are worse than no comments.

An Issue Worth Study
Unfortunately, I am not aware of any scientific studies that have been done to measure the effectiveness of various coding or comment styles. Considering the tremendous amount of money invested into software development each year, the financial benefits of optimizing coding standards based on a critical analysis could be substantial.

I would like to see such a study performed. I envision that the study would start with a series of common code comprehension tests for all participants to serve as a baseline and then the various coding styles for a series of solutions would be spread across the participant pool with comprehension speed and quality measured. When normalized against the results of the baseline tests, I am hopeful that useful trends could be drawn from the results. Are there any researchers willing to take up the challenge for such a study?

Where do I fall in the debate?
I have been developing production software since 1981, when adding comments had a very physical manifestation, literally keypunching an additional card in the punch card deck for each comment line. Over the last 30 years I have read source code from hundreds of developers across the full spectrum of coding and comment styles in multiple languages. I have seen the good, the bad and the ugly of software source code.

I generally fall into the pro-comment camp. The software blocks that I have found easiest to understand are those which have a multi-line block comment at the top to explain the general approach and intent of the developer and then specific single line comments throughout the code at the start of each new logical step of the algorithm. This is how I comment when I write production code.

Comments have value and are a justified expense. Comments need to be maintained with the same diligence as executable source code. Comments should be treated as a professional responsibility and offensive comments should be treated the same as offensive verbal speech. Company policy and code reviews should enforce this approach.

As a useful tool, I would like to see a program made available that produces API like documentation from source code but also includes all the inline comments as a separate section of the documentation page. High quality comments would give a clear picture of the purpose of the routine and a natural language narrative the specific algorithm contained with the method. This would be very helpful when provided in addition to the information normally provided by API documentation tools. Comments could be independently reviewed for quality and standards compliance.

What do you think?
Has source code comments been an issue for you? Where do you fall within the comments debate? Have I neglected to address an particular point? I am very interested in your position on this issue. I invite your comments.

About the Author

Joe Kunk is a Microsoft MVP in Visual Basic, three-time president of the Greater Lansing User Group for .NET, and developer for Dart Container Corporation of Mason, Michigan. He's been developing software for over 30 years and has worked in the education, government, financial and manufacturing industries. Kunk's co-authored the book "Professional DevExpress ASP.NET Controls" (Wrox Programmer to Programmer, 2009). He can be reached via email at joekunk@ajboggs.com.

comments powered by Disqus

Reader Comments:

Thu, Feb 13, 2014

http://www.maddonnasnashville.com/o DOT nline_casino.php http://www.frugalmoose.com/ DOT http://www.maddonnasnashville.com/v DOT iagra.php http://www.maddonnasnashville.com/c DOT ialis.php http://www.yldiablog.com/ DOT http://w DOT ww.comparelifeinsurancedeals.com

Sun, Feb 2, 2014

http://www.insurecaronline.com/ DOT http://www.globemedgeorgetown.com/ DOT http://w DOT ww.termlifecoverquote.com http://www.menshealthprice.com/ DOT http://www.abwheminn.org/ DOT

Tue, Jan 28, 2014

http://w DOT ww.medspricechart.com http://larsbolanderblog.com/b DOT lackjack.html http://www.healthinsurcover.com/ DOT http://b DOT aapalsa2013.com http://w DOT ww.cheapinsurancemate.com http://y DOT ankeegold-anovel.com http://www.myhomeinsuranceplace.com/ DOT

Wed, Jan 22, 2014

http://w DOT ww.mylifeinsuranceguide.net http://w DOT ww.cheapinsuronline.com http://w DOT ww.allstatescarinsurance.com http://w DOT ww.findairflights.com http://www.buyfirstmedication.com/ DOT http://y DOT ouroptionshere.com http://w DOT ww.gettopedmeds.com

Sat, Jan 18, 2014

http://w DOT ww.getcheaphealthinsurance.net http://w DOT ww.medformen.com http://y DOT ouroptionshere.com http://w DOT ww.insureyourbusiness.net http://www.mycheapinsuranceonline.com/ DOT http://f DOT orexlikepro.com http://w DOT ww.cheapautoinsurcover.com

Tue, Jan 14, 2014 Hollie http://www.bestautoinsur.net/ DOT http://w DOT ww.lifeinsurancpricing.com http://w DOT ww.allhealthinsurers.net http://www.quotesmanager.net/ DOT

http://www.bestautoinsur.net/ DOT http://w DOT ww.lifeinsurancpricing.com http://w DOT ww.allhealthinsurers.net http://www.quotesmanager.net/ DOT http://www.gettinginsurancequotes.net/ DOT

Fri, Nov 8, 2013 Titia car drivers insurance young

http://www.carinsurquote.net/ DOT

Thu, Oct 17, 2013 Earnhardt news mobile

http://www.csulbrotc.com/ DOT http://www.shippingtv.com/ DOT

Tue, Oct 15, 2013 Xexilia website news

http://www.d-mann.com/ DOT http://www.getrue.com/ DOT

Wed, Sep 18, 2013 Blue best credit card

http://www.travelrewardscards.net/ DOT

Wed, Feb 15, 2012 niall

Commenting the Class is usually enough in my experience, as long as the methods and member variables are named accurately. I rarely read comments on methods written by others. If the methods are kept short enough <20lines or so there should be no need for comments. Unit Testing also helps where you can read what is expected into a method and what is expected out. The Unit method should be linked in the comments of the method being tested.

Fri, Feb 18, 2011 dennis Belgium, Antwerp

If you're sure you don't make mistakes you don't need comments. But You're only human so you will make mistakes. Writing comments forces you to think about what you actually created. It's a way to double check yourself. The same principle goes with writing comments on paper in a meeting or while studying. It is just part of the human process to create something that works...

Tue, Feb 15, 2011 Dave Jellison Orlando, FL

I typically completely ignore comments (if present) when reading someone else's code. It's been well said in a few remarks, code doesn't lie, and comments can. I've also been writing code for a decent amount of time and can assure you I'm not an amateur. I have the luxury of writing most products from scratch these days but have worked on small and large team development endeavors over the years. I never write comments anymore. I’ve gone back to complex software I’ve written 6+ months ago and been able to read my code quite well (and usually want to refactor in the new knowledge I’ve gained in the last 6 months). It’s not about having a big ego it’s about expressing your ideas clearly in code and code alone. I completely agree with Paul Kimmel small, well-named methods are a key to this strategy. I name all namespaces, classes, methods, properties, fields and yes even local variables in an easily readable, self-defined verbiage. If a software developer following me does not understand English, the point is moot since I could only comment in English. The developer would understand as much (or as little) from the code as they would from the comments. I’m not totally anti-commenting. If you write code such as Sort(bool ascending, bool lastNameFirst) then by all means, please keep commenting your code because the next person (including yourself) will need a comment when they see you call your method as Sort(true, false). I proposition instead of spending the time writing the comment, you take the same amount of time it would take to comment and write extension methods such as SortAscendingByFirstName. That’s just a thought and personal opinion and we all know what that’s worth. I’m about as interested in a flame war as trying to convert a VB.net evangelist into falling in love with C#. If you code, do it well. If you comment, do the same.

Sat, Feb 12, 2011 Doug Rosbury

Any comment is only someones opinion and cannot apply to anyone but the opinionator or the commentor, words are not facts. words are only noises or symbols and should never be taken as truths. And this applies also to these words. As the old saying goes, "actions speak louder than words" For that matter, words, not being actions, have no power at all.---Doug

Mon, Feb 7, 2011 Greg Sohl

I'd just refer you to my blog post, Why you should comment the "Why" (http://www.cwi-websoft.com/blog/2009/02/04/26/)

Wed, Jan 26, 2011 LaTiNo Netherlands

It's ridiculous to think you can skip all comments. We don't need to comment obvious stuff, but there are a lot of situations in which business exceptions or something like that make you do unexpected or rather unlogical things that need explaining. If you think it's not necessary it's bc you are lazy or because you are an arrogant genius who thinks everybody should be as smart or you or die. This kind of stuff will be very nice to have when you have to maintain somebody elses code: //in this case we need to create a second, slightly different record in another table because this and that department needs that or \\Ms Word doesn't deal this very well so let's trick it by doing.... \\when two customers are in the same household, we need to transfer all debts to that customer with the highest income for tax purposes Furthermore, function/variable names that describe it's meaning or purpose well are a big plus too And yeah, comments might get outdated if you don't update them, but that's a matter of discipline, if you don't do it it's YOUR fault, not the fault of the comments!

Tue, Jan 25, 2011 Arnold Rolling Meadows, IL

"Comments are a clue as to what the developer was thinking when (s)he wrote the comment." As long as you keep that in mind, comments are useful to have. But I'd rather not duplicate info in a comment that is already evident in the code. Sparse, value-added comments - good; comments for the sake of comments - very bad!

Tue, Jan 25, 2011 Buddha Dude Code Nirvana

I have gone so far as to force my developers to include a program level synop that not only includes dates, names and a brief overview of the whole application, but also includes:
• Programming language (vb6 or C#)
• Compiler Version (VS 2005)
• Compiler service packs and patches

I have had developers patch a developer machine and compile and app, then put it on a server and it not work, or, a developer checks out a project onto his machine and the code does not work, by checking the synop against the developers machine or server, we can tell if different versions are there; this was a real issue in VB 5-6

I also make the developers put meaningful comments when checking in code.

Sun, Jan 16, 2011 Joe Kunk Okemos MI USA

Ralph from Calgary makes a good point about named parameters. I agree that they significantly improve the readability of the code by self-documenting the method calls when used with well-named parameters. These are available in Visual Basic using the "ParameterName:=value" syntax and in C# 4.0 using the "ParameterName:value" syntax. I am not aware of any disadvantage to using them and adopting this practice should be strongly considered to improve the clarity of the code and potentially reduce the number of comments in the calling method.

Sun, Jan 16, 2011 Joe Kunk Okemos, MI USA

Wow! What a fantastic discussion. Thank you all for reading and responding to this article. It is amazing to see that this truly is an international issue. The responses make many excellent points. I especially appreciate the perspectives from the anti-comment camp, from the developers that have been writing code for decades, and from those that have experience outside the .Net languages. I tried to write a "fair and balanced" article by limiting it to exactly 3 points on each side; it may be fair criticism to say that my anti-comment points were a little weak since I fall personally into the pro-comment camp; if that is the case, please understand that it was not intentional. It has been a pleasure to read these responses and I look forward to reading any new ones that come in. Happy Coding! (notice I did not say Happy Commenting!)

Sun, Jan 16, 2011 TATWORTH

I recommend getting Submain's GhostDoc Pro to produce the essential documentation framework. Once this is done, fill in any essential comments as part of the XML documentation. Spell checking comments is a good idea!

Wed, Jan 12, 2011 Chris Shaw torrance, Ca

With regard to commenting computer code, ask yourself: Is there absolutely nothing you can say to help the next programmer understand this piece of code? If no, don't comment. If yes, comment.

Wed, Jan 12, 2011 Mark

Anti-Comment. I comment only when it is required for understanding (which is almost never). And I'm not a beginner. I wrote my first program in 1966. I've used many languages on many platforms. My current language of choice is Delphi Prism on Windows. Combined with Silverlight/WPF, it is a great platform. I typically find the C family of languages hardest to read. Not sure why. But I have found the Pascal family of languages easiest to come back into old code and know what it was doing. I think the bad thing about comments is that they get out of date. Usually, you don't have a clear idea of how to implement something until you have tried it 2 or 3 ways (usually found as you debug problem areas). If you right the comments from the start, the "mission" may have changed by the time you end. I could MAYBE see adding comments after the fact. For an Api, for instance.

Wed, Jan 12, 2011 CJ Au

Several people have already said it, but if it's still a debate then it hasn't sunk in.

Comments. Are. Important.

Obvious to you isn't obvious to me. I've seen code and just sat there with a blank look on my face for a few hours trying to figure what the hell they were on about. Sure, when it finally clicked then yea, it was obvious. But it wasn't at the start and no-one is good enough that they can code something that's so obvious everyone gets it right off.

Commenting that i++ increments is bad, of course. It's just _that_ simple that it doesn't need to be commented. But anything above that does. Libraries may go out of date, compilers may have issues that get fixed. Change is the one certain thing in coding, and your obvious program to someone who was in the same class at uni might not be so obvious to someone who graduated 20 years later and has never even heard of the style you were using.

Different uni's teach different styles of coding, people who aren't in uni might pick up yet another from a book.

So summing up, obvious isn't that obvious so help out a fellow coder. Or don't even do that, help yourself out later on when you want to know why you did what you did.

The only people who might disagree with me are people so lazy they can't write two sentences on the side. And they should be fired.

Wed, Jan 12, 2011 Sathish Kumar J, INDIA

Every professional developer know how important commenting is. This is a useless debate. Do you think any medium to large size projects are developed withouth comments. Only beginner level developers who mostly work in very less complex projects wont comment.

Wed, Jan 12, 2011

I'm in the pro comment camp. When I'm writing something, all of the names I've assigned to variables make sense ... but six months later ... I'm not so sure. Describing what a routine does is helpful, and that can be accomplished by naming the routine appropriately. But for me it's in-line comments that are most helpful because they tell me "Why" I decided to do a certain check now

Wed, Jan 12, 2011 Garth new Zealand

While i have seen places where comments have been useful, "if you change this in a way that looks obvious something unexpected will happen" in general comments clutter the code that is writen by experts for experts to read, my guess is that for every time a comment has added to my understanding there have been an equal number of comments that clouded my knowledge of what is actually going on, I almost never read the comments until I have an understanding of what the code is doing

Wed, Jan 12, 2011 Colin Dick Bezier, France

When you write BUGFREE code that NEVER needs to be maintained THEN and only THEN can you stop commenting. 80% of program costs are in maintainence, comments are for the next coder to understand WHAT & WHY, you did things the way you coded. The HOW is in the code. The odd GOTCHA could also be commented to warn the coder.

Wed, Jan 12, 2011 Matt London, UK

Amateurs produce code without comments. It is as simple as that. To say that it is too much effort to comment code is rubbish. I comment code as I write it; it took about 2 days of imposing that disipline upon myself and it has been second nature ever since. But then again early on in my professional career, I made sure I could type by studying RSA and Pitmans. It makes a big difference when you don't have to keep looking at what your fingers are doing!

Tue, Jan 11, 2011 Ravikumar S India

I say comments are really helpful in understanding the "why" this code is.

Tue, Jan 11, 2011 Ralph Calgary

I think an IDE could be very helpful here. I think the IDE/language should support (at least) 3 levels of comment. 1) Beginner. For those who are unfamiliar with the code. Show all comments. 2) Normal. Show only comments meant for those familiar with the code. Such comments explain cryptic code and give comments on the function of large blocks of code with in a method. (Many would argue that such blocks should be separate (and thus named) methods with named (in Smalltalk at least) parameters thus avoiding the need for comments. 3) None. Show no comments. Switching between code comment levels should achieved with a simple button press. Users would usually be in Normal mode. If you step into code that you have trouble following you switch to beginner level, read the comments until you are comfortable with it and switch back to Normal. If you are brilliant, or very familiar with the code, or are doing some intense thinking with regard to a method trying to find a bug or improve the code then you may become so familiar with the code that you can decide the comments have become clutter and turn them off by switching to level 3. The IDE should remember what setting you used for each method and set the comment level according to the last time you visited the code or your default setting if you never visited the code before. Perhaps a level 0 could also exist which would show a comment specifying what a method does to method users. Admittedly, having to support two or more comment levels would be a pain but, I believe, worth it. I would suggest that the programmer write the normal level comments as (s)he writes the code. The beginner level comments could be written before, during, or after the code is written depending on circumstance, programmer style, and/or company policy. My style would be "mostly after" because I tend to do a lot of refactoring and I don't want the beginner comments to become out of date before any beginner even gets the chance to see them. This is in fact how I comment now. Comment for my self first, comment for other developers second. Both sets of comments are (equally) important. Regards, Ralph

Tue, Jan 11, 2011 Ralph Calgary

(Warning long post) While no one can be completely against comments I kind of fall into the anti-comment camp. I am a Smalltalk programmer and, to my mind, most Smalltalk code typically has too few comments where too few means practically none. But in Smalltalk we (mostly) get away with this because: 1) Smalltalk is a (good quality) object oriented language and object oriented languages tend to result in more readable code. (I don't want to start a flame war here.) 2) Smalltalk uses named method parameters (except, arguably unfortunately, the first parameter where instead the function is named). Named method parameters make code much easier to follow and make comments much less necessary! They are a great idea. I have never understood why most of the object oriented languages that came after Smalltalk abandoned named parameters if favor of C style argument lists. Being more C like is not necessarily a good thing. We computer scientists are supposed to be pretty smart but we really dropped the ball here in my opinion! The word "idiots" comes to mind. I am not trying to start a flame war here, really! This is an issue I feel very strongly about; if you don't agree with me, fine. I wanted my say, and I've had it. Having read/written many thousands of lines of Smalltalk code with very few comments I can attest to the advantage of methods not cluttered with comments. Comments can really slow you down when looking at code to understand what it is doing!!! Admittedly, if a method is particularly difficult or long, a few short comments may be justified. And if cryptic mathematical equations or logic are used then comments are usually needed. But such situations are rare in most code.

Tue, Jan 11, 2011 Hans Cairo

No code without comments! At the time code is written the developer delves deep into all the details and everything is fresh and clear. Maybe you tried separate approaches to a problem but one was not not working, the next one was too slow, so finally you decided to use what you see in the code. It's impossible to derive from the final code what *shit* happened with your first tries. I especially appreciate the idea of writing your intentions first, and then the code to implement it and then to get both in sync.

Tue, Jan 11, 2011 Randy

I work with software that mostly consists of complex business rules applied to individual records. I work from a set of well defined requirements and business rules. I create comments at the top of each operation and then put the business rule ID's in the code. This keeps the comments small and shows the business needs expressed by the code.

Tue, Jan 11, 2011 John Melbourne, Australia

I'm a believer in comments. I like to document my code in blocks at the beginning, explaining WHAT the code is does, the parameters, etc. Also, like some others here, a section in the block with WHY. The why tells the next reader so much more about the purpose of the code, than mearly what it does.. I highly recommend placing WHY sections into the formal requirements of any code commenting you make. Treat your comments as the documentation for your API and your whole attitude changes.

Tue, Jan 11, 2011 Br.Bill

By the way, I just spent 3 weeks trying to make fixes to programs written completely sans comments by someone who thought their code was "obvious". It isn't. Even beautifully designed naming conventions don't make your code obvious to everyone. Nobody else knows EXACTLY what you know.

Tue, Jan 11, 2011 Br.Bill

Re: "Comments are apologies for writing poor code." This is what people who never have to maintain other people's code say. I have 25 years of development experience in very diverse environments, and that experience says this statement is untrue. On top of that, you aren't always in charge of what is stupidly developed. If you have to make a call to a library that is provided by, say, Microsoft, the names of the method/function/class/etc. don't always make good sense. Neither do the mechanics of calling it. People who don't comment think they live in a vacuum.

Tue, Jan 11, 2011 Matt Los Angeles

A couple of rules I'd like to state: 1. be very good at reading code. You should be able to read any code and understand WHAT it does. Comments can be wrong from the start, so when fixing a bug, you certainly should treat the code as the source. (Sometimes you'll find the bug by comparing a comment to the code.) Never rely solely on a comment to tell you WHAT the code does. 2. WHY something is done cannot always be deduced from code, so that is where a comment is vital. 3. The understandability of code is primarily determined by naming and design. Since design intention cannot always be shown through naming, commenting must be used to fill in the gaps. E.g., someone comes along to fix a bug and doesn't understand that a certain design pattern was implemented, so they fix the bug, but end up breaking the design. 4. Code reviews can be used to test understandability. Comments should be added as necessary to impart understanding when this test fails. Proper name selection is equally responsible for understanding.

Tue, Jan 11, 2011 peterchen

Um hello? Anti-Comment Point #2 and #3 are just silly (sorry for the surprisingly passionate wording). Just because I *can* write "Diamonds are metal" as a comment doesn't make them bad. That's like saying "we shouldn't use variables, because I can declare some that I never use, and that's bad". The only point that deserves an extra squiggle of thought #1: it does not affect runtime behavior. A simple reply would be "Variable names don't. Using goto doesn't. Even Rewriting the app as a perl statement emitting machine code doesn't". The remaining question is: can code be crafted as maintainabe without comments? The only study I know is that there's an ideal length of identifiers - readability decauys with short, as much as with long identifiers IIRC the optimum weas around 8..16 characters. Which pretty much limits the information you can put into an identifier. string defaultTitleToBeUsedWhenThereIsNoLocalTitleAndNoSpecificTitleInAnyOfTheParentNodes is a no-go.

Tue, Jan 11, 2011 Chris TN

"It was hard to write, it should be hard to read..." :) Adding to Joe the Plumber's comment, I've seen a 3rd camp: "With a mind to self-preservation, I want to make it as difficult for others to replace me and will comment only upon pain of death." Silly, but I've seen plenty of examples with current employer. I'm pro-(concise-)comment.

Tue, Jan 11, 2011 Max Peck Daytona Beach, FL

Someone earlier said that comments are an "apology for writing bad code". I could not disagree more. The comment sections of code, if done well, are an excellent place to explain to the next developer (or yourself) the intent of the code and a great place to write down (scratchpad) what your thinking process behind the code is. I've been at this for 35+ years now and I still comment as liberally as I have always done. I can't count the number of hours that it has saved me when I come back to some obscure routine I wrote and right there is a clear explanation as to why I did what I did. Without those well placed "scratchpad" notes it is really tough to figure out what the intent, or at least what the methodology might have been at the time. My view has always been that since the comment sections cost the compiler nothing, then comment away baby! Of course I do agree that putting comments like "increments counter" and things that are completely obvious can be as bad as not commenting at all.

Tue, Jan 11, 2011 Tim

I believe comments are essential. Having said that, I also believe that the variable and method names should be as descriptive as feasible. I comment each method as to what it does, and comment on each of the input parameters and what the function returns.

Tue, Jan 11, 2011 Dennis Washington, DC

I am a serious pro-comments advocate. What we call "comments" are not simply comments. It is a form of DOCUMENTATION, and it is critical to the long-term health of the application. Unless you have complete certainty that no one is ever again going to look at your source code (including youself), no developer should ever assume that the next developer is going to understand his or her code. (And if you have that certainty, then you might as well throw the source out.) We all must document what we have done and why. And the documentation must be gone is straight-forward, understandable English (or whichever language is appropriate for the location). While we in theory have other documentation (e.g., design and requirements), way too often they get shortchanged in the cycle. And even when we do have them, source code documentation permits the developer to point directly to how the real meat of the project (the application) meets the design and requirements. I have spent countless hours on many occasions trying to figure out what a snippet of code is for, and that time could have been saved if the previous developer had bothered to spend a few extra minutes (that's all we are talking about) thinking about the reason he just wrote what he did.

Tue, Jan 11, 2011 Stefan Switzerland

I'm pro-comment. I agree with Mark in that at least 2 of the anti arguments are silly. I think I've seen better ones, but that is not the point of my posting. I've found that every comment is only so helpful as it's writer is willing to make it. Lazy comments in the style of "i++; // increments counter" are redundant and pointless. Many people don't get that a comment shouldn't state what the actual code does - it should state what the code should be doing, and possibly why, in case that isn't obvious. To that end, it is usually best to *first* write the comments, and afterwards the code. If you do it the other way round, there is a big danger you keep documenting the obvious and don't actually make your code any more understandable than it already was. How much comments are needed depends. Sometimes it's good to have a half page of comment on a one-liner, simply because you can put only so much information into variable and function names, and the simple operation you invoke might not so obviously achieve your intended goal. Other times it's ok to skip comments entirely, if your function is so basic that it's structure and names speak for themselves. As a rule of thumb, I always ask myself: "if I'd come across that code in a year, would I be able to understand how it works, and why it's being done this way?". Because revisiting code I've written before and trying to understand it is the most common use of the comments I write...

Tue, Jan 11, 2011 rayastray

Great coding sometimes requires a few comments. Pro comment arguments: (1) Wouldn't it be silly for an author to claim that including an illustration always indicates weak prose? Sometimes it's the right tool for the job. Same with comments (2) Sometimes you need to explain why another algorithm wasn't used.

Tue, Jan 11, 2011

ROC on dudes! Comments should, imo, explain the purpose of methods etc. These comments rarely fall out of date. Otherwise, comments get in the way. It's 2011. ROC on!

Tue, Jan 11, 2011 kasper

Comments are appologies for making poor code. Most comments explain that the code will behave bad under certain conditions ets. Use you time to write good code rather than poor comments.

Tue, Jan 11, 2011 Rick McMullan DC

A while back I needed to write a diff routine--a program that comapres two text files and reports the differences. It sounds easy but it's not. AFter a few failed attempts, I looked at the GNU diff routines. They did not help at all. I could see the code and I could see it working but I could not understand how. I finally had to go to an ACM article in the diff header. You can read it here: http://read.pudn.com/downloads131/sourcecode/delphi_control/558602/O(NP).pdf. ANYway, to make a long story short, I spent the next day or so trying to understand the algorithm. Finally I was able to implement it (in FORTRAN!) But there was no way I could have understood what the code was doing without having read that paper. Somethings are not that obvious. Sometimes there's location labeled "and the magic happens here". And the only reason I knew to look at that paper were the comments. So yeah, comments are good. Yeah.

Tue, Jan 11, 2011 Naibedya Kar India

I like to see proper comments in the code. This make the code complete. We would be just like a man in the desert without proper file headers, funcion header and inline comments if we will check the code after some days of development. It is true that writing comments do take some time of the deveoper, but on the other hand we need to see how much time we are saving while checking or changing the code in future.

Tue, Jan 11, 2011 Brian UK

Interesting that the anti-comment people actualy replied, there case is clearly so good that no comment is required :)

Tue, Jan 11, 2011 Peter Netherlands

My position: 1.Do not comment the obvious, like /* open the file */. That kind of comment is useless. 2.Do not comment each and every line. If you could almost compile your comments, there's too much detail. Comment blocks of code to make it easy to identify steps. 3. Having said #2, commenting is no justification for large chunks of code. Split methods and functions before the outgrow readability. 4. Document algorithms and main lines of thought where the real magic of the program happens. A large portion of each program is necessary housekeeping and that doesn't need comments, but if the magic is built on considerations not directly implied by the code, put a comment block on top to explain it. 5. Don't use TODO comments. TODO's never got done.

Tue, Jan 11, 2011 j5c England

I always start with the comments; saying what I think ought to happen and how to use the code that is being written. Then I write the code and verify that it matches the comments. If they differ, I have to decide which is 'correct' and modify the other one. If you don't have a clear idea of what you want to happen, then you will never achieve it. It is so easy to get bogged down in the details when coding that you can lose the big picture. Writing the comments first ensure that the big picture is still visible. My source is usually over 50% comments as I use it as documentation and requirements as well as the 'how and why'.

Tue, Jan 11, 2011 Michael Kingsford Gray South Australia

Good code, with verbose variable names, do NOT require comments. If one feels the need to comment then either: 1) You are doing it the wrong way or 2) You are abbreviating your naming schemes 3) Your are employing the abortion of naming prefixes, such as prefixing your variables with a cryptic type. This means that you are using an untyped language: a fatal error.

Tue, Jan 11, 2011 Dave Toronto

I am actually anti-comment. When I am looking at code that someone else has written, I find the comments distracting, especially if there are too many of them. I prefer to just look at the code to see what's going on.

Tue, Jan 11, 2011 Matt UK

From my limited experience I guess the problem is that people who write low quality code also write low quality comments. In other words comments add no value when most needed. People who care, take time over their code and read books/articles like this are probably making judgement calls on whether or not a comment will add value. The result of these judgement calls will vary but probably not have a dramatic effect and the overall outcome.

Tue, Jan 11, 2011 Alexander Ukraine, Kiev

I'm pro comment, but when it's necessary. A simple example: public void Load(string login){...} It has no sence to comment such code, when it just loads object by user login. But: /*Loads user by either login or EMAIL*/ public void Load(string login){...} Essence is to focus attention that both variants: login or email can be used to load user.

Mon, Jan 10, 2011 Ed Indiana, U.S.A.

Pro-comment. I obsessively comment code, even code that I expect no one but me to be maintaining in the years to come. I make my comments as detailed as possible to explain, to myself, what I'm expecting the routine to do, and HOW it is doing it, as well. God forbid I should have to try to decypher code written by someone of the single character variable name, no comment mode of coding wrote 5 years ago.

Sun, Jan 9, 2011 Peter Vogel Canada

The problem with commenting code that "isn't obvious" is that there is no metric for "not obvious." Not to mention that what IS obvious to the person creating the code may be completely opaque to everyone else (Kernighan and Ritchie refer to programmers whose "write only" code is like love letters to the computer and, like all love letters, are only really understood by the two people involved). I still think that what must be documented is "the why" the code exists--everything else is optional and is probably best handled through good (and standard) programming practices.

Sun, Jan 9, 2011 Mark North Carolina

Part 2. So assuming you are using an OO language, an IDE (not VI) and a code repository, code comments are good when you need to explain something that is not obvious in the code when all good coding techniques have been exhausted. Just as duplicate code is bad, so are comments that duplicate the code. Again, I am not talking about API documentation. Still one must be very careful with API documentation. I was reviewing someones code recently and because of the API documentation at each method and field, it was almost impossible to see the code, let alone follow it. It also made reading the comments difficult to read. Basically I agree with Pro points 1 & 3. But these do not mean everything should be commented with textual comments. The best way to comment your code is to keep methods and classes small, use names for fields, methods and classes that express what they are for and do and use proper scoping for fields, methods and classes. Comments are not a replacement for good coding. A lot of reasons given by the commentors here are due to this. As Peter V said, referring to business requirements and TDD are better for documenting code than inline textual comments. I would add in example code too as this will show usage and not muddle the source code. Also, comments are not for saying who changed what and when. That is what the code repository is for. If you are not good at writing code that can be understood just by looking at it, then, by all means, comment your code. But if you can, get some help from someone who CAN write good code. If you cannot write good code, how do you think you will be able to write good comment? Sadly, we have too many people typing out code who, IMHO, might be better off not. But that is utopian thinking and who gets to decide.

Sun, Jan 9, 2011 Mark North Carolina

Sorry this is long and hopefully the line breaks will show up. Also, i had to break up my posts. Given only two choices, I would be in the anti-comment camp. I don't think, though, that this camp was very represented by the author. The pro-comments reasons seem reasonable while the anti-comments seem “less than reasonable”. To put my views on comments in to a few word: Only important comments are important. I do not believe this discussion can be held in vacuum by excluding language and tooling. In fact coding style, code purpose and code availability must also be included. These are all evident by the previous comments to this post. Some of us have the advantage coding with technologies other than VB.NET and./or VS.NET that allow us to be able to see this As is evident in the comments here, code comments are often confused with documentation. For instance, class level and method level comments are typically documentation, not comments. Depending on your platform these may not be necessary if they add no value. Sometimes they may be needed only for external documentation. If I have access to the source code, when maintaining the code, the first thing I do is look at the code. If I cannot figure it out, THEN I look the comments. Well, first I sigh and think bad things about the developer.

Sat, Jan 8, 2011 Jay McClellan Michigan

I comment my code extensively because I'm forgetful, selfish, and lazy. I mean that! I honestly can't recall what I had for breakfast yesterday, but I can glance at code I wrote 5 years ago and instantly know what my thought process was when I wrote it. And more importantly, so can anyone else which means that any junior programmer can maintain my code and that frees me to go have fun creating the next new thing. And after developing software over the last 20 years I've come to believe, without mathematical proof, that start-to-finish I can ship good software faster by documenting it well than by documenting it poorly. It may be counter-intuitive to believe that typing a comment can save time in the long run, and for some people perhaps it's not true, but for me it means long-term efficiency and that means getting more accomplished with less effort.

Sat, Jan 8, 2011 Drewes Kooi

I am against too many comments, a few here and there where it is not obvious why or what you are trying to accomplish is fine, the rest just clutters the code. Proper formatting and naming of variables and functions are essential, adding comments and stating the obvious is not. A brief summary at the beginning of the code is good, for the rest I wouldn't trust the comments that someone else made, i would not be sure if they were being maintained so the actual code is the final word for me.

Fri, Jan 7, 2011 Scott Florida

Pro-Comment #4: Intellisense. I've started (and encouraged in others) adding XML comments to all public subs/functions in classes, and to any properties that are the least bit non-standard. Then when I'm writing a program tomorrow or 6 months from now, or someone else is, it is instantly obvious from the Intellisense tag what will happen. I don't need to go dig up another project or two to read the code inside the class, taking time away from my original coding, and perhaps losing my train of thought. Instead I see what the sub/function/property really does, instantly.

Fri, Jan 7, 2011 Timothy New York City

Ha, ha...I think of how you would explain you last girlfriend to someone you haven't met yet. Honestly, I've read some code that looks like the person went to the bathroom and never came back. Just like variables, there should be some top level description. My only rule...if the description is longer than the code then something is wrong.also, the important thing is to document change and reasons. but why would you need that at the code level? if you have to explain basic code to the next person then they shouldn't be changing your code to begin with. Your code reflects your persona. You're either a Felix Unger or an Oscar Madison.

Fri, Jan 7, 2011 Peter Vogel Canada

I think that the last word on the subject was actually written many years ago in "The Elements of Programming Style" by Kernighan and Ritche (and a book that programmers should re-read every year). They point out that a comment is of zero or negative value if it's incorrect. If you comment what the code does then you end up with two descriptions of the processing: one in code and one in comments. The danger here is that, like the man with two watches, you'll never know what time it is. Obviously, if the two descriptions disagree, only the one in code matters. The key, then, is to avoid "write only" code and create "Really Obvious Code" (ROC: ROC Rocks). What needs to be commented is what the code (and code analyzers) can not express: The business purpose of the code--WHY this code exists and what drove its design (e.g. that the code is written this way to reduce memory consumption). That might best be handled by referencing the business requirement that drove the code (but that assumes that those requirements exist). In a test driven development environment, commenting the tests and referencing the tests might be the best way to go since the tests are driven by the requirements. Comments are really just part of the larger discussion on the value of documentation.

Thu, Jan 6, 2011 Rickeeee

The 2nd and 3rd "anti-comment" points are silly. They amount to saying that comments shouldn't be written because they are sometimes written (or maintained) badly. Well, program design is sometimes done badly, so is testing. It hardly follows that we shouldn't do these things. The weakness of relying on self-documenting code is that it only tell you WHAT the code is doing [e.g., "GetUrl()"], not WHY it is being done. If you tried to pack the 'why' of a method into its name [e.g., "GetUrlBecauseTheResourceMightBeRemote()"], you'd have a method that can only be used when that same 'why' applies. When you are getting a URL for any other reason, you'd need another, identical method with a different name.

Thu, Jan 6, 2011 Tom

I'm Pro Comment. Good points made in the article as well as the comments here. I would add one more thing which has already been somewhat implied: When commenting it is important to explain WHY a section of code was written in the way it was. For example I've seen code that had a redundant (and seemingly) unecessary stat such as assigning a var the same val twice in a row. BUT when the redundant line was removed, trouble materialized (turned out to be a compiler issue which was later resolved in a future release). So the WHY's are impt.

Thu, Jan 6, 2011 Richard Melbourne, Australia

I favour comments. There are other things than just explaining the code, such as who wrote it, when and why. It lets you find all the changes made for a particular release easily. Commenting what variables are being used for can help in writing the code as well as maintaining it - it keeps clear what their purpose is.

Thu, Jan 6, 2011 SteveH Minneapolis

I'm pro comment. Code should have an aesthetic quality to it. Without that quality, code reviews are painful at best. Also, documentation tools that extract from the code base are extremely useful, but do require maintainance of comments as well as code (con comment camp). Alas, such is the technical debt we pay.

Thu, Jan 6, 2011 Joe the Plumber

My experience with developers that don't comment code is that they fall into to two camps. The first camp doesn't comment code because “the code is so obvious that it doesn't need explanation” or the second camp follows the logic "I don't understand the code and what it is doing so if I put in comments I will display my ignorance"

Thu, Jan 6, 2011 RichM Florida

I'm in the pro comment camp. When I'm writing something, all of the names I've assigned to variables make sense ... but six months later ... I'm not so sure. Describing what a routine does is helpful, and that can be accomplished by naming the routine appropriately. But for me it's in-line comments that are most helpful because they tell me "Why" I decided to do a certain check now.

Add Your Comments Now:

Your Name:(optional)
Your Email:(optional)
Your Location:(optional)
Comment:
Please type the letters/numbers you see above

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.