I used to think commenting my code was the responsible thing to do. I used to think that I should have a comment for just about every line of code that I wrote. After my first read of Code Complete, my views changed pretty drastically.
I began to value good names over comments. As my experience has increased, I have realized more and more that comments are actually bad. They indicate a failure. In Clean Code Robert Martin says
“The proper use of comments is to compensate for our failure to express yourself in code. Note that I used the word failure. I meant it. Comments are always failures.”
Those are some pretty strong words. You may be reeling back a bit after reading that. It is a normal reaction, but if you’ll drop your defenses for a second, I’ll help you understand why.
Let’s start with an example
Which is more clear to read? This:
int i = 5; // Start at 5, since there are 5 widgets in our production system. // If the number of widgets is evenly divisible by the time, // and we have exactly 5 sockets we need a new one. if((i % this.t) == 0 && s.Count() == 5) { i++ }
Or:
int currentWidgetCount = DEFAULT_PRODUCTION_WIDGET_COUNT; if(ShouldCreateNewWidget(currentWidgetCount)) { currentWidgetCount++ } private bool ShouldCreateNewWidget(int count) { return CountEvenlyDivisibleByTime(count) && SocketCountAtThreshold(); }
Even though the second example is more code, the code is self-documenting. The names of the variables and methods themselves are telling you what the code is doing.? They are also serving to abstract out the concepts so that you don?t have to think about the entire piece of logic at one time.? This simplifies your code.
In the above example, you don?t have to look at the method ShouldCreateNewWidget.? You can deduce that the flow of that logic checks to see if it should create a new widget based on the count, and if it should it does.
If you want to know how it is determined if a new widget should be created, then you drill into the method, and you can see that if the count is evenly divisible by time and the socket count is at the threshold, then the answer is true, otherwise it is false.
Consider again the first example.? What happens if that logic changes, but the comments aren?t updated?? When you read the comments, how do you know that they are even correct unless you read through and understand the logic anyway?
Why are comments so bad?
It is not that comments in and of themselves are bad.? It?s more that having comments in your code indicates that your code itself is not clear enough to express its intent.? Elegant code should be able to express itself simply and completely.? Comments are not code, they are metadata about the code.? If you want to write elegant code, write elegant code, not elegant prose about code.
Here are some of the major reasons why comments are bad:
- They do not change with the code. If a refactor tool changes the code, it cannot change the semantics of the comments, it can only change the syntax where it can recognize keywords.
- A wrong comment is worse than horribly complex non-commented code. A wrong comment can lead someone completely in the wrong direction.? For that reason, a good developer always assumes comments are wrong.
- A comment almost always expresses an absolute thing, where a well named variable or method can express an abstract concept. Comments can actually tightly couple your code.? Take the example above where int i = 5 had a comment stating that 5 was the default.? DEFAULT_PRODUCTION_WIDGET_COUNT communicates the same information, but at a higher level of abstraction.
- Comments don?t show up in stack traces. I have looked through many stack traces in my career, and I can tell you for a fact, that when you are looking at a stack trace, you would much prefer self-documenting method names, than good comments.
- Reading comments is optional. Reading code is mandatory.? You cannot count on anyone reading your comments.? You cannot force them to do so, but they must read the code. If you have something important to say, put it in the code.
NDoc and JavaDoc (XML style comments)
I am moving more and more away from even liking comments on public methods using JavaDoc or NDoc.? Most of the time when we create NDoc style documentation, we end up just restating exactly what the parameter name is.? How useful, really, is: cookieCount ? the count of cookies? Does that actually help someone using your code?? I would much rather make method names that have intuitive names and parameters than follow an arbitrary convention that adds no real value.
There is even a tool that auto creates NDoc comments for you.? Seriously, I used to think that was cool, but really how stupid is that?? Auto-generating comments?? Before you disagree with me here, really think about if embedding XML into your source code is really adding any value.
I understand creating MSDN style documentation is pretty cool.? I?ve used NDoc and SandCastle myself.? But, wouldn?t the effort be better spent creating more meaningful names and self-explanatory APIs?
Exceptions
Sometimes, you will need to write comments.? But, it should be the exception not the rule.? Comments should only be used when they are expressing something that cannot be expressed in code.? If you are using some mathematical equation, you might reference that equation in a comment, rather than trying to codifying it.
If you want to write elegant code, strive to eliminate comments and instead write self-documenting code.
Update: Just wanted to add this link to my original post on Elegant Code. And the link to my main personal blog at http://simpleprogrammer.com, since some people were getting confused.? Also, you can follow me on twitter here.
Very nice article, however your 2 links at the top for, “Code Complete” and “Clean Code” aren’t working by clicking on them.
Great points, I totally agree. Even on the XML documentation, I’ve even been stripping that junk out of older classes when I go in for modification.
It’s so nice to open a file and see one, small, readable class that says exactly what it does — without the clutter!
There’s one thing though that you should consider. This is definitely a step in the right direction, however it is only half of the challenge. Meaningful code self-documents “what” the code does, but does not express “why” the code does it. Bugs crop up for any number of reasons, but pretty much all bugs share one thing in common, the code isn’t doing what it’s supposed to be doing.
What expresses to the reader what the requirements are, and more importantly, how the code meets those requirements? Well, that’s sort of an easy question: The requirements of course. The second half of the challenge is to express the requirements in code, and probably the best way to do that is to build behaviour-based tests along the same principles. The code self-describes what it does, while the tests self-describe what the code is supposed to do. All nicely compiled together instead of relying on separate documents. Just as comments aren’t compiled and soon can lose relevance to the code, requirements documentation suffers the same fate.
@Beddet
Whoops, Fixed the links. Thanks for letting me know.
@Steve Py
Thanks Steve, I agree with you 100%. That might be my next post. I like how you call it the what and the why.
I wrote about this topic & integrating tests as part of the desing a couple months ago: http://py-sty.blogspot.com/2010/02/descriptive-code.html
I had a recent experience in device driver land in which a large function was doing a bunch of only vaguely related things during hardware initialization. Each little section was preceded by a one line comment explaining what it was about to do. I factored out each section into a function with a self-explanatory name, and things became a lot clearer, with less comments (the comments became function names, essentially.)
OTOH, in device driver land, sometimes you have to write big long comments describing some weird, non-obvious behavior that your code is dealing with, which, without the comment, would lead the reader to think, “why the heck is it doing things this way? This is insane! It could just do X instead!” Except X doesn’t work because *whatever non-obvious reason*. Yeah, sometimes the hardware can be pretty weird. And sometimes the kernel interfaces, (or library interfaces in user land) can be just as weird.
often I put comments in when I have to do things in a suboptimal way because of the behavior of other things (dependencies, external systems, whatever). Sometimes it’s bugs in the other areas, but sometimes it’s just an impedance mismatch.
I try to comment just enough to preemptively answer the questions/comments/concerns that would crop up during a code review (of course, assuming ‘fixing’ it isn’t an option for whatever reason 🙂
I have have just finished Code Complete (2nd Edition) about a month back so I feel I need to point out that Steve does not exactly come out against commenting at all. In fact he recommends using commenting as a sort of psuedo-code to design your function and filling in the actual code underneath. They are also useful to explain rationale – especially when there are multiple ways to do something and you had to choose one for a particular reason.
However, I agree to your points regarding the dangers of comments. There is also another way that code commenting is (mis)used – it is used to comment incorrect or unneeded code. I have blogged about it here .
Elegant code is more than just avoiding comments – there is a zen to coding that leads to Beautiful Code . This kind of code has a clarity and balance that makes whatever comments are there a natural part of the code. Writing Beautiful Code is a labor of love 🙂
Talking of expressing yourself in code instead of comments:
I do agree with you, it’s the code that should talk. Sometimes it’s hard to express your intent properly in code though. But looking at your example: What’s so bad about stripping the unnecessary if/else block and just
“return CountEvenlyDivisibleByTime(count) && SocketCountAtThreshold();”?
I think the if/else block is unnecessary clutter and I really dislike it, and this is why: a) It’s a trivial boolean term and easily understood, b) the if/else block adds no value in terms of readability c) since you often see both, an if/else reflecting and an if/else block inverting the outcome of the condition, all you get is two nearly identical looking patterns with opposite result, which can be an evil trap if you’re in a hurry and need to change or understand things. Well, this is just my humble opinion.
Anyway, nice blog, I just subscribed to your RSS feed.
I wholeheartedly agree. Within our team, we stress readability and self-documenting code over comments. The only place where we use comments is exactly in the parts where we need to “compensate for our failure to express” ourselves, where we’ve deviated from standards, or implemented something hacky that was unavoidable which requires justification beyond what you can see in code.
Don’t underestimate the importance of brevity. Identical code:
int currentWidgetCount = DEFAULT_PRODUCTION_WIDGET_COUNT;
if (ShouldCreateNewWidget(currentWidgetCount)) { currentWidgetCount ; }
private bool ShouldCreateNewWidget(int count) {
return (CountEvenlyDivisibleByTime(count) && SocketCountAtThreshold());
}
Oddly, your blog’s comment system seems to strip pre-increment.
I disagree, comments can be useful in so many situations many of which do not indicate failure. For instance, I am trying to push our code to be commented so that something like Doxygen can provide a good API for our scripters. Right now method arguments of certain functions are misunderstood because you can only get so much across via a name.
Comments help you so that someone does not need to look into your implementation to see how the method works. At that point it is a failure.
Interesting post, and I’ve considered much of this myself. I agree with many of the cons of comments, however, providing a CHM file for an API can offer incredible value. This isn’t possible with XML comments. If the CHM is important and considered a priority, developers would have to be disciplined to maintain comments just as they would have to be disciplined to create self-documenting code. I’m just saying, both can be valuable.
Another example is in organizations with heavy documentation standards. My current client actually copies/pastes code int Word documents. It goes without saying what a waste of time this is. I’ve been lobbying for XML comments and a Sandcastle generated CHM in lieu of this, which could save a ton of valuable time.
In short, your post makes sense 100% to me, but there is still value in XML comments for other situations.
Holy war! 🙂
I agree overall, but I see the role for comments in two places:
1) documenting hacks (as in: “// HACK- hardcoded for now, at some point use widget for this”)
2) documenting APIs or key interfaces. However, I don’t like the “tactical” comments as in “cookieCount – the count of cookies” but I like one comment on the interface itself that explains the intent of it, key dependencies, and other more “strategic” information that will be useful later and doesn’t really get out of date the way “tactical” comments always do.
It’s not a zero-sum game. Good comments and good code are better than just good code, if only to understand what the author intended to do or thought was happening.
Comments should be unnecessary 99% of the time. The times that warrant them are when context is needed for the decision at hand, or when working with legacy code from life-support perspective. Comments in new code is a failure of expressiveness.
“Reading comments is optional. Reading code is mandatory.”
What is the reasoning here? Comments are intended for human consumption, code is intended for machine consumption. If anything, I’d say that reading comments is mandatory, reading code is necessary. Comments tell you the intention of the programmer, while the code only tells you how he happened to implement it.
For instance why is ShouldCreateNewWidget implemented as it is? “Wouldn’t it be a good idea to always create a new widget? What the £$¤% is this Threshold and why is this relevant *ctrl-click to read the implementation of that method, then find your way back again* ok, what?!”
Besides, saying “this is a bad idea let me show you an example. this is much better here is an example of that” and then adding in other things that are established as good practices (meaningful variable names, extracting logic into separate methods) but not part of your claim really undermines your argument. Why didn’t you write the commented version in black text on black background as well? That would -really- show us the advantages of self-documenting code!
I agree with your main point, but have to disagree on XML comments. GhostDoc saves time in filling in the template; the developer is still expected to flesh out the comments.
I’m currently working with a third-party API where we have no access to the source, only the generated autodoc help. Apparently no XML comments were used, and it’s terribly frustrating. Where are the examples? What exceptions can be thrown? Is the code thread-safe? What are valid argument values? When should this method be called? For example, one of the parameters is bool isPrimaryLogin. OK, but what does “primary” mean in this context?
Providing good XML comments on the public API can go a long way towards making libraries easier to consume.
For your “self-documenting” example, you probably want:
bool ShouldCreateNewWidget(int count)
{
return CountEvenlyDivisibleByTime(count) && SocketCountAtThreshold();
}
rather than the if () { return true; } else { return false; } nonsense.
That’s a cute example, but good comments explain why, not how.
for example..
if(someVar == null)
{
doThis();
}
else
{
}
@Randy
Damn, hit enter by accident…
..the moment has passed so long story short; semantics behind code choices need to be explained regardless of how good your variable names are.
I agree with the rule that code should be self documenting wherever possible, but I don’t think it should be taken to the extreme. In this example, I personally feel the single comment that explains what’s happening in concise English is better than splitting the code up so much to try and make it self documenting.
If you imagine a whole class written like this, the reader would have to keep jumping between methods to figure out how any algorithm works. They’d have to maintain a “stack” in their own heads to unravel the functionality, when perhaps a one or two sentence comment would tell them everything.
I think there are times when English is simply better at describing what is happening than code and in those situations, commenting is better than writing more code.
@Chris
Thanks Chris,
You are right. Several people mentioned that. I will go ahead and change that in the main post. For some reason when I was writing the code, I was thinking there would be other conditions there, but it ended up being just those two.
@Randy
I agree, but that is what unit tests are for.
@Anu : Certainly that is a risk. However, if you follow a base principle that a method should do one thing, and one thing well: and that method is self-documenting, there is no call stack to trace through to understand what is going on. Sure, method A may call B, which may call C, but you will find the bulk of understanding what’s going on is organized.
public void SaveCustomer(Customer customer)
{
if (customer == default(Customer))
throw new ArgumentNullException(“No customer provided.”);
ensureCustomerIsComplete(customer);
ensureCustomerIsUnique(customer);
_domain.SaveCustomer(customer);
}
SaveCustomer saves a customer. It relies on methods to ensure that customer is complete and unique. The code is easy to understand, and the rules it uses are re-usable, and if the customer level of completness or uniqueness comes in to question, you know precisely where to look. There is no need for additional comments to explain “what” is happening. However, as I and others have eluded, and John’s acknowledged, this doesn’t cover the “why”.
“Why” was the driving principle behind my initial drive in support of “good commenting”. Code said “what”, comments said “why”. Then I read a bit, and realised that comments lie, and they lie easier than code. Just as I might have started with a method called “ensureCustomerIsUnique()” then realised that I also needed to ensure that the customer was complete as well: I could have simply added the complete (all required fields filled in kind of thing) into the ensureCustomerIsUnique method, but then the self-documenting nature would lied about what the method was doing. It would be doing two things, not one. Merely adding comments to express that second thing, or even renaming the method still leaves me with a smelly method.
Comments lie, not from day one, but as the application matures, comments become “optional”. They don’t affect the performance of the application, they aren’t necessary to update to compile and run the application. Even the “why” of code can be expressed in code through automated tests expressing the requirements. You change the code so that it doesn’t match the “why”, and tests fail. Sure, you can choose to just comment out the broken test, but that’s a very deliberate act of wrong-ness, that is easily detected and punishable by Donut!
@Steve : I do agree that high level methods should be written in the controller/dispatcher style as you’ve posted above (I’m sure there’s a name for it). I use it wherever I can and they generally never require comments.
I guess I took the example in your post too literally. What I meant was, when it comes to the lower level methods that really just “do one thing” (like the example in the blog post) if you split it up into multiple, non-reusable methods just to have explanatory method names, it actually becomes more work for the reader to understand it.
So yes, the higher level methods should definitely follow a self documenting pattern, but I think there is an obvious limit to how much you split up the lower level methods.
The first example is clearer, at least if you use a trick—the trick of ignoring all the comments. It remains a better starting point for a real solution:
int widgetn = 5;
if(!(widgetn % this.time) && sockets.Count() == 5){
i ;
}
Of course, widgetn could probably be even shorter, maybe even wn, if it was fed from a meaningfully-named function.
Ultimately, the biggest reason comments obscure code is because they space it out. Giant long names and premature abstraction does precisely the same thing.
John’s example is a bit confusing because if its simplicity. I’m sure he has more meaningful examples contained in production code but that’s not exactly something that’s prudent to publish on a personal, public blog. 🙂
My own comments on the subject hinge on moderation. It’s not to say I never write comments because I accept that writing elegant code is accepting and fostering the evolution of code. The initial forms of the solution of a problem are not ideal, they’re riddled with assumptions, missing bits here, and superfluous bits there. This code is typically heavily commented with notes, assumptions, and lots of “Whys”. (I’m not a TDD, I’m a TSD [Test-Soon-Dev]) As the assumptions are confirmed as facts or discarded, the code is cleaned out and re-factored. Behavioural tests are added to reflect the solidified requirements, and comments are deleted. Maybe I can’t justify the time/cost to re-factor everything so some comments may remain to warn of Dragons. Some would argue that this solidification should happen during a design phase, before meaningful code is written; However I subscribe to the belief that code and tests are the design, the running, working application is the deliverable.
http://www.intotheweb.org/?p=960
Comments are not inherently bad, but comments that simple describe the code are generally undesirable. I think a good use of comments is to describe why something is the way it is. There’s almost always more than one implemented an algorithm, so a comment about why you choose than method can be quite useful (especially if you already tried another method and saw it fail).
Excellent work John. Steve’s comments are well written and thoughtful. Without tests to describe (and document) the evolving whys and wherefores – even greater pressure is put on naming, SRP, and other clean code practices.
I wrote about this very topic here for anyone interested: http://applanet.com/2007/01/Documenting-System
Great article. Names, names, names – I’m telling you if I had 1 penny for every time I advised someone to change a name of variable or method because it wasn’t clear, I would be rich.
Not only do clear names improve the clarity of the code – but they can possibly further develop your ability to generalise and become more abstract – a skill I value highly.
Working with programmers who aren’t usually English can be interesting though.
Sorry but you FAIL. Method names should be meaningful, with your “little” improvements they aren’t anymore. Your first chunk of code is actually more elegant.
Comments often give very useful information about the overarching purpose of the method in the grand scheme of things, but code that simply describes an algorithm is stupid. I think it’s very shortsighted to simply say that “all comments are bad”. If I’m in a huge application, and I don’t understand the business rules or the business domain, well-thought comments regarding where the code stands and how it relates to the business domain in the larger scheme of things can be very useful in helping new team members get their bearings.
And remember, even if the methods and variables are named correctly according to the business domain terminology, that doesn’t necessarily mean that the reader of the code understands the business domain. In that case, comments are there to define the business terminology when the definition in code is not necessary.
If your in a ‘huge’ application perhaps it should be best that the application have design and functional specifications document’s so as to be able to keep the code clean. Then the “Developer” can understand the code & application functionality BEFORE even breaking into the code itself.
If you really need comments then they should be put within the comment blocks that show on the intelisense within your VS IDE.
I would agree with this author that to create //comment within the lines of your code is messy and should not stay there.
I think this article talks about bad ways of adding comments to the code.Code and script can do lot of tricky things which other developers or analyst any one reviewing the code will find difficult to understand.
But comment always help or at least at the method level try to describe what you are trying to accomplish.Obviously you need clean code which is more self documenting, But i would still have the right comments in place.(not on every line of code)
Otherwise soon you will soon see your clean code becomes difficult to read through by time or when the size grows.
Love this article – I have long promoted this. I even went so far as to say “Comments are bad” in a session only to have to get into a huge debate on it.
Method names also need to be descriptive – it’s all about the name.
Comments do have their place – but most comments can be left inside Source control systems and spec documents. That said, I like what Shazbot said:
“If you really need comments then they should be put within the comment blocks that show on the intelisense within your VS IDE.”
That’s why I added a rule into my refactoring tool to say any code where the comments are 1/3 the size of the code, needs to be refactored immediately.
Love this article – I have long promoted this. I even went so far as to say -Comments are bad- in a session only to have to get into a huge debate on it.
Method names also need to be descriptive – it’s all about the name.
Comments do have their place – but most comments can be left inside Source control systems and spec documents. That said, I like what Shazbot said:
If you really need comments then they should be put within the comment blocks that show on the intelisense within your VS IDE.
That’s why I added a rule into my refactoring tool to say any code where the comments are 1/3 the size of the code, needs to be refactored immediately.
The non-trivial software product will have many levels of abstraction. At the lowest level there are the actual code statements, over that there are methods, then classes/interfaces, components/packages/assemblies/DLLs, layers, clients/servers/tiers etc… and these are just “physical” levels – there may be many domain-specific “logical” paradigms with no direct analog in the programming language/technology.
While I agree that commenting at the level of statements is usually superfluous (i.e. the code can usually express itself AT THAT PARTICULAR LEVEL OF ABSTRACTION), properly documenting all the other levels has great value for long-term maintainability of the product, which is where some forms of comments have their rightful place.
The rules of thumb for good comments are:
1. The comment should be AT HIGHER LEVEL OF ABSTRACTION than can be expressed directly in code.
2. The comment is usually written BEFORE code.
Here are some examples:
– Commenting the API is absolute must – the client will usually not have the access to the source code and not all of the pre/post-requisites for making a particular API call can be expressed through the language / communication technology chosen to implement the API. Typically, the best the API implementation code can do is throw an exception / error code, but by that time the high-level context for understanding the root cause of the problem may be lost.
– Everything is “API”, even if used by the same person/team. The software I usually work on is usually too complex to keep ALL the nitty-gritty details in my head. There is a great value in being able to FORGET the code that I’m not currently working on. Having high-level comments all over the place serves as a “shortcut” for understanding the code I now no longer need to read.
– Commenting intention – as code evolves, having a proper documentation on what is ESSENTIAL, versus what is INCIDENTAL lets me stick with essentials and break less clients as code evolves. In fact, well written comment will change LESS OFTEN than the implementation code.
– Commenting higher-level structures. Often, my data structure is a complex graph or tree of nodes, and needs to have a specific “shape” or certain things need to happen in certain sequence to have a proper behaviour. While assertions/contracts help, higher-level documentation is usually a must.
– Commenting dependencies – a product can depend on many pieces of code or even entire applications not written by me or my team. We are often forced to do certain things in a certain way simply by not existing in a vacuum. With proper documentation, it is easier to understand what changes need to be made in our code when the “environmental forces” change.
– Commenting on a choice of algorithm or data structure – there is often a situation when there are multiple choices of algorithms and/or data structures that can be used to solve a particular problem. Neither choice is “incorrect” – they all produce correct end result – by there are time/space/scalability tradeoffs to consider and the “correct” solution is the one that fits with the expected USAGE PATTERN best. Commenting what is the expected usage pattern and what are the performance tradeoffs chosen as a consequence can help tremendously in understanding performance bottlenecks when usage pattern changes.
– Comments can simply be LONGER than programming language names. Just the other day, I was tempted to make a method: “RemoveHandlesOfNotImplicitlyUnloadedModelsFromSession()”; at the end I settled for simple (but imprecise) “CleanupSession()” with appropriate comment.
Let me disagree with some of the specific points you make:
– “They do not change with the code.” – Nor the other way around. I often find myself editing the comment simply to “debug” my thinking and change the code only AFTER the comment looks right. If you code first and comment later, then I can see your point.
– “A wrong comment is worse than horribly complex non-commented code.” – True, but a comment rarely exists in vacuum. If the rest of you product is documented properly, the bad comment will be obviously inconsistent with the rest of the documentation and easy to spot. Actually, achieving “comment consistency” is useful technique for “paradigm debugging” in your head.
– “A comment almost always expresses an absolute thing, where a well named variable or method can express an abstract concept.” – Actually, my experience is the opposite. Good comments are always at the higher level of abstraction than the code.
– “Comments don’t show up in stack traces.” – No, they are one click away.
– “Reading comments is optional.” – Well, the basic OOP principle of encapsulation tells us that reading implementation code is optional as well. Without comments, what you are left with is reading names/signatures of classes/methods/parameters and that alone is often simply not expressive enough.
@Branko, you said:
“Everything is “API”, even if used by the same person/team. The software I usually work on is usually too complex to keep ALL the nitty-gritty details in my head. There is a great value in being able to FORGET the code that I’m not currently working on. Having high-level comments all over the place serves as a “shortcut” for understanding the code I now no longer need to read.”
Its ok not knowing and/or remembering the details of complex software. But if you open any given code file in such software, and you can’t easily/quickly understand what it is, it almost surely isn’t good code. You say having the high-level comments all over the place serves as a ‘shortcut’, but its usually there for the inability to use a better design. ps. I know sometimes we just have to deal with such code, but that doesn’t mean the situation wasn’t created by a different problem, ignoring that perpetuates the issue.
Your code should not contain comments. Your TDD/BDD style unit tests should tell the story. If the unit test name is descriptive it would be easy to understand what the code is doing without even looking inside the unit test itself. if your unit tests are grouped correctly, just reading the method names of the tests should provide an overview of what the code section is doing. best of all, if your code changes, your tests should fail (TDD approach) and you need to fix them, including changing the test’s name, which means your test and description/documentation always stay in sync.
This of course is in the perfect world of TDD, I do find myself commenting code when I need to fix something quickly and don’t have time to write or update a unit test, not ideal. I started off writing comments in pseudo code style comments as a way to organize my thoughts, you should use your Unit Test Class to do this in TDD style and not in the code. The only reasonable explanation for commenting a piece of code is when it needs work; i.e. better design, and to reflect that in the comment so that another developer knows when they see it that it needs better design, keeping in mind unit tests already exists for it.
imho, your blog post takes for granted that everyone writes well structured and self-explainable code. In my experience, people don’t 🙂
I rather see documentation as a tool to write better code. And now I’m not talking about writing comments inside methods, but commenting projects, classes/interfaces and properties/methods: XML style comments.
I try to explain my point of view here:
http://blog.gauffin.com/2010/06/my-name-is-more-docu-more/
Comments are not bad at all, they are just wrongly used. Because they are consider of lower importance with regards to code.
The comment should state, at least code comments, why something is done not what it is done.
If you really need comments then they should be put within the comment blocks that show on the intelisense within your VS IDE.
Um, no. Comment your code please. I small comment giving me insight to what you were thinking is worth a whole lot.
I can reverse engineer your code but I can’t reverse engineer your thoughts.
If you are too lazy to update your comments when you update your code thats one thing. Just don’t encourage others to do it.
What about the fact that there is some code that functions exactly as wished but doesn’t really lend itself to self documentation?
And in my experience, the vigorous application of this logic begins to feel like the dark side of hungarian notation.