If peppering your code with lots of comments is good, then having zillions of comments in your code must be great, right? Not quite. Excess is one way good comments go bad:
'************************************************* ' Name: CopyString ' ' Purpose: This routine copies a string from the source ' string (source) to the target string (target). ' ' Algorithm: It gets the length of "source" and then copies each ' character, one at a time, into "target". It uses ' the loop index as an array index into both "source" ' and "target" and increments the loop/array index ' after each character is copied. ' ' Inputs: input The string to be copied ' ' Outputs: output The string to receive the copy of "input" ' ' Interface Assumptions: None ' ' Modification History: None ' ' Author: Dwight K. Coder ' Date Created: 10/1/04 ' Phone: (555) 222-2255 ' SSN: 111-22-3333 ' Eye Color: Green ' Maiden Name: None ' Blood Type: AB- ' Mother's Maiden Name: None ' Favorite Car: Pontiac Aztek ' Personalized License Plate: "Tek-ie" '*************************************************
I'm constantly running across comments from developers who don't seem to understand that the code already tells us how it works; we need the comments to tell us why it works. Code comments are so widely misunderstood and abused that you might find yourself wondering if they're worth using at all. Be careful what you wish for. Here's some code with no comments whatsoever:
r = n / 2;
while ( abs( r - (n/r) ) > t ) {
r = 0.5 * ( r + (n/r) );
}
System.out.println( "r = " + r );
Any idea what that bit of code does? It's perfectly readable, but what the heck does it do?
Let's add a comment.
// square root of n with Newton-Raphson approximation
r = n / 2;
while ( abs( r - (n/r) ) > t ) {
r = 0.5 * ( r + (n/r) );
}
System.out.println( "r = " + r );
That must be what I was getting at, right? Some sort of pleasant, middle-of-the-road compromise between the two polar extremes of no comments whatsoever and carefully formatted epic poems every second line of code?
Not exactly. Rather than add a comment, I'd refactor to this:
private double SquareRootApproximation(n) {
r = n / 2;
while ( abs( r - (n/r) ) > t ) {
r = 0.5 * ( r + (n/r) );
}
return r;
}
System.out.println( "r = " + SquareRootApproximation(r) );
I haven't added a single comment, and yet this mysterious bit of code is now perfectly understandable.
While comments are neither inherently good or bad, they are frequently used as a crutch. You should always write your code as if comments didn't exist. This forces you to write your code in the simplest, plainest, most self-documenting way you can humanly come up with.
When you've rewritten, refactored, and rearchitected your code a dozen times to make it easy for your fellow developers to read and understand -- when you can't possibly imagine any conceivable way your code could be changed to become more straightforward and obvious -- then, and only then, should you feel compelled to add a comment explaining what your code does.
As Steve points out, this is one key difference between junior and senior developers:
In the old days, seeing too much code at once quite frankly exceeded my complexity threshold, and when I had to work with it I'd typically try to rewrite it or at least comment it heavily. Today, however, I just slog through it without complaining (much). When I have a specific goal in mind and a complicated piece of code to write, I spend my time making it happen rather than telling myself stories about it [in comments].
Junior developers rely on comments to tell the story when they should be relying on the code to tell the story. Comments are narrative asides; important in their own way, but in no way meant to replace plot, characterization, and setting.
Perhaps that's the dirty little secret of code comments: to write good comments you have to be a good writer. Comments aren't code meant for the compiler, they're words meant to communicate ideas to other human beings. While I do (mostly) love my fellow programmers, I can't say that effective communication with other human beings is exactly our strong suit. I've seen three-paragraph emails from developers on my teams that practically melted my brain. These are the people we're trusting to write clear, understandable comments in our code? I think maybe some of us might be better off sticking to our strengths -- that is, writing for the compiler, in as clear a way as we possibly can, and reaching for the comments only as a method of last resort.
Writing good, meaningful comments is hard. It's as much an art as writing the code itself; maybe even more so. As Sammy Larbi said in Common Excuses Used To Comment Code, if your feel your code is too complex to understand without comments, your code is probably just bad. Rewrite it until it doesn't need comments any more. If, at the end of that effort, you still feel comments are necessary, then by all means, add comments. Carefully.
| [advertisement] Peer Code Review. No meetings. No busy-work. Customizable workflows and reports. Try Jolt Award-winning Code Collaborator. |
Posted by Jeff Atwood View blog reactions
« Building Tiny, Ultra Low Power PCs Understanding The Hardware »
I agree! Comments in code are a double edged sword; they're become like more code to maintain. And if no one is maintaining them, they become downright dangerous.
I use comments sparingly, and only to tell what's being done and how. Usually in the form of one-liners.
Jaryl Sim on July 24, 2008 07:03 PMwhat the hell is a comment?
Calvin on July 24, 2008 07:29 PM[quote]And if no one is maintaining them, they become downright dangerous.[/quote]
That's just job security. I'll do one better.. insert lies and comments that make no absolutely no sense.
Relax, I kid.. I kid..
Mike on July 24, 2008 07:30 PMI've found, when looking back at really old work, that the comments were nothing more then psuedo-code typed before actually making things work.
When I look at my systems today, about the only comments I find (other then TODO stuff) are notes about the business rules being implemented by the code and even then only when the business rules are intuitively obvious.
For instance, in my current project I need week numbers. However, we base week numbers by starting from the last monday of the year before. That's weird enough to actually document as a method named "GetWeekNumberStartingFromLastMondayOfPreviousYear" is just silly.
I've heard arguments for using comments during maintinance to show what was tried, but frankly, if you're checking in your work on a regular basis, you already have that history.
Lucas Goodwin on July 24, 2008 07:30 PMHm, you should still have a comment in that code snippet stating it uses Newton-Raphson approximation, IMHO. And you definitely don't want that as part of the function name. Heck, even having "Approximation" in the function name might be putting too much implementation detail in the function name, unless you're dealing with a common code library that just *might* be picked up by engineering.
Oh, and you'd definitely also want some error margin information as part of the function comment... in case somebody from engineering even *considers* using the routine :)
f0dder on July 24, 2008 07:32 PMr = n / 2;
while ( abs( r - (n/r) ) > t ) {
r = 0.5 * ( r + (n/r) );
}
System.out.println( "r = " + r );
Isn't (n/r) always 2?
> never, ever start with comments.
Unless it's inline extractable API docs like javadoc of pydoc, of course.
John Levon on July 24, 2008 07:37 PMOne problem with your example is that it's taken from numerical analysis, where knowing HOW the computations are made is essential to judging their accuracy for various inputs. Saying "This subroutine computes X" doesn't convince anybody that it's accurate.
Which brings me to your square-root example. Your final version tells me that the code approximates the square root. However, without a comment to tell me that Newton's method is being used, I cannot know this without spending time examining the code closely and having seen Newton's method in an algorithm before. Most developers would give up well before they make that realization --- forcing them to ask you to explain the algorithm and convince them of its correctness, which wastes more of your time than it would take to write the comment.
Michael on July 24, 2008 07:39 PMThe only problem with writing understandable code is that many programmers have no idea how confusing their stuff is. Sure, it's 20 pages of unorganized cryptic statements, but THEY understood it. Surely if someone else doesn't understand it, they must be lousy programmmers.
A. L. Flanagan on July 24, 2008 07:43 PMI find that when I stub out a method, I pseudocode it first with comments. This helps me think through the logic and scope of the task and generates a roadmap that I can return to if I'm interrupted.
It seems to generate very useful comments for others to follow later.
"never, ever start with comments"
I find I write my code cleanest when I start by filling in my methods with what they ought to do in comments, then filling in what they actually do after I've got my architecture down.
And, if I comment in the API doc style of the language, I get nice documentation to boot, as mentioned before.
Nick on July 24, 2008 07:56 PMI couldn't agree more. When I was a junior developer I used to bemoan the lack of comments in code created by my more senior team members. Now that I am a lot more experienced, a lot of comments tend to clutter up the code and reduce the comprehensibility.
Generally, comments tend to be wrong, or confusing. In addition, there is a tendency to comment code that is changing, or complex. When that code is modified further, the comment becomes out of date, but the instinct is to leave the comment in "just in case". Before long, nobody knows what a comment means, or why it could possibly be there.
The best comments are like the ones shown in the article. Short and to the point. If you are implementing a particular algorithm, then say so (perhaps with a link to an article explaining the method), but don't overload the reader with useless detail that is covered in the code.
Gwyn on July 24, 2008 07:59 PM"It's OK to end up with comments in your code, but never, ever start with comments."
Just as others, who have already mentioned it, I too write comments before writing a line of code, as a way of helping me think things through; and I see nothing wrong with that.
I find a lot of your blog posts useful for generating discussion - it's your frequent dogmatic conclusions that make me wonder if your head has grown a bit big...
I think comments are important because most of the programmers actually out there working are pretty hopeless. I may be able to write well-structured, clean code but the rest of my team won't understand it because they're very inexperienced. However, they're all we have.
The same happened to me when I tried to open up DNN when I was new to ASP.net. Beautifully written code, not a single comment, full of bugs. I couldn't make head or tail of it.
Leave the comments on for all the people who aren't brilliant, tireless programers.
Dan on July 24, 2008 08:09 PMI will side with the people who say that badly maintained comments are worse than no comments. Comments in the code *are* code and need to be maintained as such; but there's no compiler or interpreter to tell you about the dependencies.
My own code tends to be tersely commented at best; the one time I remember writing about 25 lines of comment for three lines of code was because those three lines were getting around a bug in Windows 3.1 and there was no URL I could point people at to read about it...
Most of my comments contain the url from where I stole the particular bit of code from. Tests explain things much better than comments can. "Talk is cheap. Show me the code."
Brennan on July 24, 2008 08:16 PM> Just as others, who have already mentioned it, I too write comments before writing a line of code, as a way of helping me think things through; and I see nothing wrong with that.
Not quite the same thing, unless those comments stay in the code after you've written it!
Jeff Atwood on July 24, 2008 08:19 PM> Your final version tells me that the code approximates the square root. However, without a comment to tell me that Newton's method is being used, I cannot know this without spending time examining the code closely and having seen Newton's method in an algorithm before
SquareRootApproximation(n, Type.NewtonRaphson)
Jeff Atwood on July 24, 2008 08:21 PMYou can save on writing comments by designing every piece of software around a concept of software factories vomiting objects but looking really understandable, by-the-book academically cool.
Or you can write compact code, based on well thought-out usage patterns, not some over-engineered ego-busting monster that compiles, runs but cannot be reused.
BugRree on July 24, 2008 08:23 PMKey problem: some comments can't be expressed through functional decomposition.
I agree that algorithm and data structure explanation should be done largely through functional and OO decomposition and member and type naming, and that this is one of the big reasons why naming is so important, but there are other aspects to programming than call-tree decomposable algorithms and trivially modular data structures. Not all problem domains and corresponding solution abstractions are representable in a first-class way using the tools of structured programming and object-oriented design.
What about global[*] state changes that affect horizontal sections of code, rather than the vertically-oriented call tree of a functional decomposition? [* or local to a large object graph - functionally not all that different]
What about concurrent programming, where every cross-thread-visible operation is only correct when every possible relevant state of every other thread has been considered?
What about older programs written in older languages using older techniques - I'm thinking of IDE compilers written in C with extensive global state, discriminated unions and semantic field reuse across different stages, in particular (since it's my day job). A few comments go a long way in these kinds of situations - particularly since one doesn't have the luxury of writing it correctly the first time, even presuming that the right abstractions are available in any single programming language.
Code that has been maintained for decades generally doesn't have an immediately understandable gestalt such that it can be immediately refactored and rewritten more clearly, and in these situations comments are vital to help build up that gestalt, so that future refactorings can occur.
Motivating example: you've got a data structure graph that represents a parsed piece of code, and you've got to do manipulations, optimizations, debug info extraction, and code generation - and do it all as fast as possible with minimal copying and reallocation etc. Classes don't sit well with the requirements - you want to separate out your parsing logic, debug info, optimization, code generation, etc., rather than lumping them all into a single class. Each of those phases will want to annotate the graph for its own purposes, but those annotations can go away when the phase is done. You end up using discriminated unions or something similar, along with functional pattern matching or a visitor pattern, etc.
I can assure you that that code (and data structure types) will improve with the addition of a few comments :)
Barry Kelly on July 24, 2008 08:24 PMI'll remember to do this but perl's plain old documentation is so cool.
j on July 24, 2008 08:25 PMI too like to start with comments if I'm writing a new function that I'm not quite sure about. Otherwise I agree.
The other real problem I see is when people don't keep the comments up-to-date with the rest of the code. As the 'what' changes, the 'why' can change as well. It's frustrating when the code says one thing and the comments say another. Which one is right?
And if the code evolves in a way in which it becomes self-explanatory, then by all means, take the comments out.
Brian on July 24, 2008 08:27 PMI wish someone would tell this to my High School and University programming teachers...
Sean on July 24, 2008 08:29 PMThen the .NET Framework code must be bad because I have to comment my code just to document how the framework works. Why can't we just go back to COBOL? That code was perfectly readable.
Robert S. Robbins on July 24, 2008 08:34 PMWell, lately I realized that starting to write code with comments doesn't help as much as starting to write code with unit tests first.
And that's why I like TDD.
Jon Limjap on July 24, 2008 08:39 PMI think there's something to be said for starting with comments. McConnell gives a thorough explanation of why you should, in fact, start with comments before even writing code in chapter 9 of Code Complete 2.
In short, you start by roughing out the design of the function/method/whatever in pseudocode. Then you rework and refactor the pseudocode until it's as plain as day what you're doing. Only then do you write the code needed to implement the pseudocode. At the end of the process you've still got the pseudocode there to act as comments.
Why delete it? It certainly helps maintenance developers and is a great check to ensure you actually coded the routine you intended to code.
Anyhow, this is just a thumbnail sketch of why you should use comments. For a much better (and more persuasive) argument, check out McConnell's book. Every professional developer should probably already have a copy anyhow.
keith twombley on July 24, 2008 08:39 PMI always try to incorporate both ideas in my code. For example, I would write the square root approximation function as
SquareRootApproximation(n)
//Newton-Raphson approximation
{
...
}
> SquareRootApproximation(n, Type.NewtonRaphson)
That's just silly, Jeff. You are going to parameterize the algorithm in order to avoid adding one simple comment? You suggest making the function's interface - and possibly it's implementation - more complex to avoid a comment? That's what I'd call a coding horror.
I have to agree with Jason Bunting. Either that, or you are trying too hard to be controversial and drive traffic to your site.
David Avraamides on July 24, 2008 08:45 PMI think to be more precise, your statement should be: comments must reflect and explain the code exactly, all the time.
I don't care going through a very long comment IF IT HELPS me in the end.
It's not wrong to start with comments. If you can't put to paper what you intend to do, how are you going to start coding?
astigmatik on July 24, 2008 08:59 PMA time when comments are a great and wonderful thing:
Given
1. Code you didn't write, but need to visit briefly to fix a problem
2. You spend more time than seemed reasonable to figure out what the hell the code was doing, and it wasn't obvious
Drop a line of comment in with your discoveries so that the next poor sod who has to visit that code won't waste an hour of THEIR life figuring out what the heck is going on.
{ Before anyone mentions that it would be better to fix the crap: 1) in real life, you don't always have time to change code to be perfect, and 2) if you do have the time, rewriting code to satisfy an ideal isn't the best use of the limited number of hours in one's life, unless it will somehow recover some of those hours at a future date }
You're way off the reservation with this one. :)
With the Newton-Raphson approximation comment,you knew which method of approximation was being used. There is no way your refactored method name is clearer than that
And I find junior developers hardly ever write comments.
Crimson on July 24, 2008 09:07 PMAlso, we need to end this myth that code is EVER as clear as well-written English. This is patently false 100% of the time (your Newton-Raphson approximation example as proof is insane :) ).
That said, if comments are explaining "obvious" code (for some definition of obvious),then it's probably not necessary. However, I've yet to be on a software project where *too many* comments/documentation/etc was an issue. I'd love to have that problem.
Crimson on July 24, 2008 09:13 PMI'm going to have to disagree with you too, Jeff. Commenting before you code a method body serves to let you flesh out the method before you spend the time to write the code for it. This ensures that you write what you intended to write, as you have the comment to look back to if you get stuck. Extracting API documentation from your code comments is a beautiful, beautiful thing. That means actually putting API documentation comments in your code.
In a previous entry you complained about the verbosity of code, but today you're advocating it in order to reduce "unnecessary" comments? Something doesn't quite add up.
Jeremy Privett on July 24, 2008 09:22 PM@fodder
i agree with you...
but may be because im just a junior developer...and im not being sarcastic :)
may be experience will make me realize what Jeff and Steve are trying to say out here...mind you Jeff's SquareRootApproximation(n, Type.NewtonRaphson) is very legible, but there are times when self explanatory function names are not possible. It just saves me a lot of *slog* with some intelligent comments(or for that matter, even some unintelligent ones)peppered here and there.
Selecting a lighter shade for comments in the IDE makes life a lot easier for me(replacing default dark green in VS2005 to a light blue) to avoid those huge huge blocks of comments from bugging you.
Jeff may be you post one on IDE color scheme. Since your post on consolas font has helped me a lot.
I have to agree with David Avraamides up there about your approximation code.
I code primarily in PHP, and my site uses quite a few includes, so I have to comment to remind myself where certain functions/variables which are being called are located.
Will on July 24, 2008 09:26 PMIt's rather silly to see so many comments against comments...
Well written comments, or even well placed comments, can save lots of work.
Relying on procedure names to comment?
Steve on July 24, 2008 09:28 PMI usually use the <remarks> section in c# to explain the why of a method if required.
I do not write many comments except for particularly arcane functions and classes. Sometimes, and Im sure Im not alone, I dont know exactly the best way about doing something but I figure a logical way of doing what I need done. It may not be the best (because I Was not aware of a built in function or a method used to arrive at said conclusion), but it works. However, it works in a very difficult to understand manner (well maybe its just me). This is where I throw comments in.
But quite frankly, Ive maintained code that had comments plastered all over the login scripts. Are you kidding me? First year college students understand login scripts, why the hell are people commenting all over the place?
Mostly I avoid comments, but then I dont use stupid variable names like $b (or var b or Dim b or whatever). Of course, I wouldnt use SquareRootApproximation either (probably sqRtAppx which is perfectly understandable to me).
Adam on July 24, 2008 09:44 PMToo many or wrong comments = bad
so no comments at all = good? What? How about well written and maintained comments that explain what you are doing? (not how you are doing it)
Comments are important, even though in many cases clearer coding does the trick instead. The idea of comments explaining the "why" instead of the "what" is nice, but I think I have an even more convincing argument in favor of comments, which runs as follows.
Code, clear as it may be and with the most elegant of naming conventions applied to it, can only ever document itself. That is, such rare self-explanatory code can only document what's there, never what's not there. What's not there is all the different (usually naive) ways the original coder tried to write the code your reading, that were wrong for some reason. The role of comments is thus to explain those inherently unintuitive cases were code isn't as simple as it might have been in a perfect world. All those hidden pitfalls owing to bugs, support for some legacy design or a 3rd party workaround; all those algorithms that were tried and were found imperfect for the job (that some smarty-pants newcomer may wish to retry on his first day unless warned beforehand); etc. In all these cases, information critical to understanding the "what" hides in the "what not", and can only be exposed by explicit documentation (e.g. comments).
Assaf Lavie on July 24, 2008 09:57 PMI agree with you Jeff. At least that his example:
"SquareRootApproximation(n)"
is more than adequate. You may argue that if by looking at the code and reading the procedure name you should almost instanly find that you're getting squareroots and using an approximation method. The comment will NOT explain the why unless you write a huge comments that honestly defeats the purpose. If the person reading the code is not current with his/her maths... They'll end up looking it in wikipedia comment or not. The difference is that the people that will "see" the code at first glance wont lose their time. And the people that don't get it will end up in the same wikipedia page with the comment or with well named objects anyways.
James on July 24, 2008 10:02 PMI have yet to run into to code which was too commented.
Jared Parsons on July 24, 2008 10:25 PM'never, ever start with comments' .. what a load of bollocks. if more people started with comments that outlined what they were attempting to achieve maintenance would be a heck of a lot easier, and so would spotting their bugs.
While I agree that ideally you want to end up with self-documenting code, more often than not you're writing rubbish on the first pass. And, pragmatically speaking, sometimes, a first pass is all that it gets until you have time to go back over it. When you do have time to go over it, those comments might help you or someone else refactor more efficiently.
It seems more often than not that people don't write what they mean to write, so comments should help spot bugs and they act like a checksum. In a code review if someone spots the comments differ from the code, then it can be followed up on.
Or just be like everyone else and write code for yourself with little regard to others. Don't unit test. If it compiles it must works. Phooey.
Just because some people drive like idiots, do you ban cars, or do you punish the idiot?
chico on July 24, 2008 10:26 PM> SquareRootApproximation(n)
> //Newton-Raphson approximation
Sure, this is fine too; I only listed my version as a counterpoint to "you must add a comment otherwise nobody will know what approximation you're using".
As I said in the post: "If, at the end of that effort, you still feel comments are necessary, then by all means, add comments. Carefully. "
> if more people started with comments that outlined what they were attempting to achieve
Again, this is not at all what the post is about. Unless those comments remain in the code after you've written the function. I'm tempted to delete that sentence because so many people are misunderstanding it.
Jeff Atwood on July 24, 2008 10:40 PM> we need to end this myth that code is EVER as clear as well-written English.
Really? Most of the english I read online is anything but well-written. At least code *compiles* (or interprets, if that's your cup of tea).
Jeff Atwood on July 24, 2008 10:43 PM
James -
I disagree. If you are relying on a well-known algorithm, you should identify the specific algorithm. Look up "Square Root Approximation" in Wikipedia, and I see nothing about the Newton-Raphson method or anything that looks like it will match the code. If I read really carefully, I see a link to "Newton's Method", which in fact does match the algorithm here. That's only after wasting a huge amount of time reading other approaches which don't match the given approach.
IMHO, always default to descriptive method names for algorithms, and always include wiki-friendly (or dictionary-friendly, or old-school-encyclopedia-friendly) terms. Therefore:
NewtonRaphsonSquareRootApprox(n)
Or:
/**
* Newton-Raphson Square Root Approximation
*/
NRSquareRootApprox()
Some purists will say "too much implementation detail", but IMHO you want that implementation detail in there. If you change the implementation to a different algorithm, it is right and proper that you should have to visit every single use of the method in your codebase to make sure the new algorithm will work as well there as the one you are targetting. And, if it doesn't, you then end up with "NRSquareRootApprox()" and "ISRSquareRootApprox" when you add in an Integer Square Root method for greater speed in some situations.
The other option, adding a constant parameter identifying the specific method, IMHO, is more clutter. The algorithm is fundamentally different, and different methods to attain similar results may require additional parameters (ex, a max iterations parameter might make sense for one approach but not another). You also end up with either an enumeration specific to that one method, or an inability for the compiler to check the validity of the enum being passed in (ie, you have implemented NR and ISR, but not BSR; what happens when the BSR constant is passed in?) The enumeration and the code implementation get too far separated in all but the simplest of algorithms, and so will get out of sync.
Tom Dibble on July 24, 2008 10:44 PMI used to believe that well-written code was self-documenting... then I started working with a lot of junior devs!!
My philosophy now is to comment almost EVERY line, explaining the business rules - I find it encourages the junior devs to think about what they are doing. (And if you don't enforce "comment every line" then (because developers are all lazy) then the comments drop down to zero very rapidly and you end up with no comments at all.)
For example:
'Get all the customers who live in this state
dim objCustomers As New Customer = Customer.GetWhere("State = 'VA')
'If there are no customers in this state...
if objCustomers.Count = 0 Then
'... then we warn the user
MessageBox.Show("You are ALONE!")
End If
Yes, the comments are strictly unnecessary but they may help someone's understanding at some point in the future, and they certainly help mine when I am code reviewing, so... they stay!!!
Syd on July 24, 2008 10:48 PM(Has Jeff jumped the shark?)
If you're saying that comments are useless if they are no clearer than the code, that's not exactly a revelation.
If you're saying that "well-written" code is always clearer than a comment, that's bo11ocks.
Comments are as much "note to self" as to anyone else:
1. I'm maintaining some code, it references some class. The code for the class is three pages long, but I just want to know what the class is there for. Shame that the guy who wrote the class (was it me?) considered that the code was self-explanatory.
2. I have a constant K_WIDTH=100. Cool, the coder was clever enough not to name it K_W. But why not 200?
3. Pushed for time, I haven't had time to refactor as I would have liked. How about a little //TODO? (Or //HACK?)
4. I'm maintaining some code, there is a 10-line procedure which could be replaced with just one method call. I think. Did the guy who wrote the code think of it? Is there some good reason to use 10 lines that I haven't seen?
5. (In C#) If I prefix the comment for my class or method with ///, hey, any client code gets extra information in intellisense. (That's even more useful if all they've got is the dll and no 'self-evident' code!)
6. I have a for loop with 5 method calls inside. Do I have to go and look at the code for the 5 methods to work out why the loop starts at 1 instead of 0?
OK, so all my examples are probably more why than how. My point is that you can ignore comments that *are* there, but you can't read comments that *aren't* there. Please don't give any extra ammunition to the 'write-once, read-never' cowboys coders who are just too lazy to make the effort.
How about you give us some examples of good *and* bad comments?
Ben on July 24, 2008 10:49 PMI read english a hell of a lot quicker than I do code, give me a well written comment any day. And sure, give the method, variable whatever a descriptive name but don't skip the title. CamelCaseIsn'tThatGreatToRead.
PS - And, yes, I still enforce Hungrarian (sic!!) notation - otherwise (especially in case-insensitive VB) you end up with variables called the same thing as your classes, which ends up VERY confusing, especially if you use static methods a fair bit.
Syd on July 24, 2008 10:51 PMOk, here I go disagreeing with you guys.
These points reflect what would be done in an ideal world. And 2 years ago, I would agree with everything said.
HOWEVER, after working on a Monster of a project for the past two years, I've began yearning for comments in code. A lot of my work deals with bug fixes in existing code and I've finally quelled my urges to simply rewrite crap that doesn't work. Here are my reasons:
- Sometimes past developers were just simply bad and there's no 'time' to refactor.
- Significantly modifying (and trust me, a lot of the modifications needed would be significant) would require retesting that functionality in the QA department. In an environment where time = money, that just isn't a viable option.
- Comments are usually frowned upon where I am ("They get in the way", I've been told). So the alternative is to sit (sometimes for hours) debugging trying to figure out what's going on.
- In my environment, the 'weird' parts of the code usually deal more with business logic and less with actually functionality. When there's a statement that says: {if A = 'CPTY'}; I'm sorry, I need a comment. Because walking over to the support department to ask "what's CPTY" isn't my idea of the best use of my time.
So, what does one do with messy code when refactoring isn't an option? I say, comment the hell out of it.
Baz L on July 24, 2008 10:54 PMYou've incorrectly asserted that too many comments are bad, as evidenced by a large chunk of useless comments. Useless comments that add nothing to the code are just that, useless. But for complex methods that take several individual tasks, I like to start out by commenting what those tasks are. When I revisit my code, I can simply read the comments to see a breakdown of each step and what I was thinking at the time, without having to ever look at actual code.
Sure, a simply for loop extracting a value from a bean and placing it in a hashtable is pretty simple to understand if you're not uses cryptic variables, but I just can't see that
//loop through bean and place value in hashtable
isn't still adding value.
I once saw a comment "confused" in one of tha web applications I support!!
Took some time to realise that this guy who wrote the code years back was refering to "XML messages sent to confused.com"
You're a year late Jeff...
Jason Monroe on July 24, 2008 11:13 PM> r = n / 2;
> while ( abs( r - (n/r) ) > t ) {
> r = 0.5 * ( r + (n/r) );
> }
> System.out.println( "r = " + r );
>
>
> Isn't (n/r) always 2?
There's a while loop there. In successive iterations r will be something other than n / 2 so n/r won't be 2 any more
Gareth on July 24, 2008 11:14 PM- Tom Dibble
Yeah the Newton-Raphson method is generally called just the Newton method. I agree in some cases it's best to append a comment explaining a little bit of what's going on. But what I meant is also something you proved yourself. If I see SquareRootApprox(n) and I know that Newtons method is the most common for approximation of square roots, then I don't need to look any further into it. But if I see SquareRootApprox(n) or // Newton-Raphson Square Root Approximation, and I don't know what it is or the specifics of the algorithm and I type either in google... I'm gonna end up reading the same thing. The only other possibility is that the programmer inserts a comment as long as a blog post explaining how the Newton method works... and that just makes everything bloated and hard to maintain.
My issue with comments is that too many comments makes everything "uncomfortable" and a hell of a lot harder to maintain. I've been in situations where I have a file maximized on my 30 inch monitor and I'm looking at huge blocks of comments and 2 or 3 lines of code. I ended up removing the superfluous comments and rewriting a big part of the code. Nevertheless, when we got new developers on board, everyone got up to speed fairly quickly and everyone praised the naming conventions and wise use of comments in the code (which where probably less than 1% of the total lines of comments previously there).
James on July 24, 2008 11:15 PMNot sure if you inspired this, or if it's just a coincidence but it's a comic that seems kinda relevant to the discussion: http://geekandpoke.typepad.com/geekandpoke/2008/07/good-comments.html
Todd McKinney on July 24, 2008 11:23 PMI pretty much only use comments in two circumstances:
1. When what I'm doing in the code seems to make no (or not enough) sense. These tend to be either things like "If you don't do this way up here, you get an Off-By-One error" or else large blocks explaining that some object's implementation is brain-dead, must be worked around, and ending with "Thanks a lot, [object vendor]". Usually [object vendor] = Microsoft, but Crystal Reports has been a suspect in the past.
2. XML comments intended for Intellisense consumption. This is a recent development for me and I'm still wary about it.
Atario on July 24, 2008 11:43 PMcomments are merely words.
Jin on July 24, 2008 11:49 PMIt’s easy to make the same mistake with your user interface.
“Oh, this interface is a bit confusing. Let’s put some explanatory text in so that users understand what’s going on.” FAIL.
Paul D. Waite on July 24, 2008 11:50 PMPi is exactly three!
Trevor on July 24, 2008 11:51 PM@Atario - 'XML comments intended for Intellisense consumption. This is a recent development for me and I'm still wary about it.'
Are you taking the piss mate, or were you just asleep for the last 7 years?
roflmao on July 24, 2008 11:55 PM"never, ever start with comments" ??
I do it all the time for almost 20 years now. Worked pretty well so far.
Ok, I'm pedantic. Maybe the last line of the refactored code should pass n as the parameter, rather than r.
System.out.println( "r = " + SquareRootApproximation(n) );
I love the Refactor menu in eclipse - it saves problems like this.
John.
John on July 25, 2008 12:18 AM"It's OK to end up with comments in your code, but never, ever start with comments." - I guess this line was edited out? Cos I can't find it in the article. Good thing too.
Andrew on July 25, 2008 12:27 AMComments are great. Take another step.
Use GhostDoc to automatically generate comments for methods (a short description with parameters, if your function has a good name, also the comment is quite good too). What do you do with this comments?
Next Step: Use Ndoc to create an html Helpfile for your Code on basis of the comments.
Next step: automate the process so that you can have a daily helpfile for your actual code. Fast to browse with keywords for new developers.
A good thing is, that if you name your classes and methods correctly you can see in the comment quite good results.
Two examples of auto generated comment
E1
/// <summary>
/// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
/// </summary>
/// <param name="x">The first object to compare.</param>
/// <param name="y">The second object to compare.</param>
/// <returns>
/// Value Condition Less than zerox is less than y.Zerox equals y.Greater than zerox is greater than y.
/// </returns>
public int Compare(Object x, Object y)
{
if (x.Weight == y.Weight)
{
return 0;
}
else if (x.Weight < y.Weight)
{
return -1;
}
else if (x.Weight > y.Weight)
{
return 1;
}
return 0;
}
E2
/// <summary>
/// Handles the RunWorkerCompleted event of the backgroundWorkerPoll control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.ComponentModel.RunWorkerCompletedEventArgs"/> instance containing the event data.</param>
private void backgroundWorkerPoll_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
You just need to add on or two lines yourself to get a code documentation. Really needed at big projects were each code is reviewed.
(The next tool in line would be something like FXCop to see if your code follows the company rules)
offler on July 25, 2008 12:29 AMI believe comments are vital for explaining _what_ you're doing and _why_ if it's not _INSTANTLY_ clear. That is, even if your routine is understandable after a minute of thinking the code through, it needs a comment because it's not immediately obvious.
In your example, I agree that you should make that its own routine for clarity, but I still would have left the reference to "Newton-Raphson approximation" in there, no matter how you organised it. You cannot possibly believe that everyone will immediately understand that's what it's doing.
I like to think of the comments as integral to the "story of the code" - Combining the code and the comments, you can see what a routine is doing very, very quickly, and that's important.
Comments are the "what" and "why" of the code, and the code itself is the "how". When properly used, they slot together perfectly and have the ability to speed up development and debugging.
Comments at the start of methods and classes are possibly the most useful comments out there - they reduce the need for heavy commenting within the code itself, explain who did what and why (useful for corporate coding and maintenance), and when you combine them with something like doxygen it can save you a lot of time hunting down someone else's code in a large code-bed.
In my experience there are developers who comment and like comments, and developers who have never given comments a proper chance and therefore hate it. Often developers take on a level of arrogance that says that their code is so perfect they don't need comments, but you cannot forget that there are developers out there at all skill levels and if you really are a hot coder, most of those guys really won't understand why you're doing something in a certain way.
BTW, some of us are forced to go through code reviews with idiots who are not coders, such as IT auditors and management. With the comments, they can get by without you having to sit there painfully explaining every line to them!
Give comments a chance mate! If they're not working for you, then your comments are BAD comments!
Simon Butcher on July 25, 2008 12:41 AMYeah. I've already talked about it: (but in french)
http://sexycoders.com/index.php/2008-03-13/pourquoi-ne-pas-commenter-son-code/
I think that comments are generally a good thing, as someone said about you can ignore the ones that are there but can't read the ones that aren't.
On my daily job I usually have tight deadlines that become tighter near the end, and that makes the code quality start to decay plus I have juniors on my team, so comments are a must. For example I just wrote:
//find cases in where this solution is relevant
//note: Last minute change, may be changed to backend at a later date.
protected function inferRelatedCases(solution:SolutionVo):String
This is not only a note to myself but also for someone in the future that comes across my code and wonders why this is here.
pedro on July 25, 2008 01:33 AMSorry to say this, but: You seem to produce more coding horror yourself than you try to prevent other from making.
Advocating not to comment your code is really not helping. Not helping at all. I have seen so many functions, classes, methods and other stuff whitout comments, where I had to read it line by line to figure out what it was supposed to to.
Of course, in such a simple example as you have given, you can probably name the function/method appropriatly to document it. Of course you should always choose self-documenting names for all symbols in your code. But in general, it is impossible to document every aspect of a class or method just by naming it right. The name can give you a general direction what it _might_ do, but in the end, you just _have_ to document all its parameters, side effects, restrictions, error conditions and everything someone who uses the code could need to know.
Of course it has to be maintained, but its just part of the whole process. You have to maintain a user manual too if you change functionality or add a feature. You can not just say: Hey, I named that button or menu really well, so I doesn't need to be documented anywhere. Again, this is true for simple cases ("OK"), but not in general.
Jeff, I urge you to rethink your approach here and not to advocate this any further. Try to think of the general case not just the simple ones (this applies to a lot of examples you have used in the past).
Weirdly, your post started out making a very valid point (tell us why the code is doing what it is, not what it is doing) but then you proceeded to argue an entirely different point about why you should refactor your code to make it is more clear what it is doing.
So great, the new refactored code makes it clear that you're doing a Newton-Raphson approximation to the square root. But I still don't know WHY you're calculating a square root, or WHY you chose the N-R method (efficiency, accuracy, something else?).
The important comment here would be something like:
// using the N-R algorithm as it typically converges quickly
// to approximately the desired root. we don't need the exact
// value here because {reason} so this gives us better perf.
Sorry for the double post :( but here's an example of what I mean. Here's a method that removes a subscription in a catch block, taken from our real codebase. It is very obvious as to what it is doing, but do you know why?
this.Unsubscribe(subscription.Id);
Now does this comment help?
// if the operation was invalid when we know the cause must be an invalid workflow queue and/or the workflow
// not existing because the only other cause from the methods in the try block is that the workflow runtime
// is not started, and that can't be the case here as we just checked. as we'll never be able to deliver the
// result to a non-existent queue/workflow then we need to remove the subscription otherwise it will stay in
// the pending work queue for runtime services that persist their jobs and cause the service to enter an
// infinite loop processing work items that it can never complete
this.Unsubscribe(subscription.Id);
As far as I understand the re-written code, it doesn't work.
't' is never declared.
Unless it's a global? And I know someone as precious as this about a simple thing like comments wouldn't go around advocating a global.
GunstarCowboy on July 25, 2008 01:41 AMI find I put one or two comments in as I am working on a couple of methods then when I refactor sometimes they become unnecessary. Once I have got to a stopping point like written a set of methods or a full class I will have a quick scan through adding in some more general comments about what a method does if it isn't apparent in the methods name.
Don't comment with pseudo code most programmers can read the actual code easily. A comment should be a sentence covering what a set of lines do so you can skip them when debugging if you know they work.
pete on July 25, 2008 01:50 AMMy first thought on reading the post title was: comments are not to be messed with.
But after reading your and Sammy Larbi's posts I took a look at my more recent code... and realized you guys are right. I still think complex code needs comments, but as you choose descriptive names for your methods the code should be self explanatory.
Posted an example of my own code on my blog: http://www.markvandenbergh.com/archives/21/no-more-comments-in-your-code/
Mark on July 25, 2008 01:50 AM> I haven't added a single comment, and yet this mysterious bit of code
> is now perfectly understandable.
Actually, no. I *still* have no idea what the hell that algorithm is and why it works. OTOH, "// square root of n with Newton-Raphson approximation" tells me all I need to know in order to be able to find more information about the algorithm, should I need it.
xxx on July 25, 2008 02:01 AMAgree 100%. If you can't tell what the code does without comments, the code isn't done yet.
Kevin Dente on July 25, 2008 02:03 AMWhats a comment? Whats "documenting"?
My 10 bits.
Comment as a prototype of the code, just to get my idea of the code out.
Replace the comments (not underneath) with the code, often being a meaningful method name.
Add comments to highlight any "quirks", notes, methods used, reasoning why. e.g. "Uses X method to do some awesome sh!t to the string", "This code is sluggish, but I cant think of a better way, tried x,y,z".
Rob on July 25, 2008 02:06 AMComments are for anything unusual in my books.
Anything that isn't immediately obvious or would look a bit "wrong" without a comment. This means that they describe either some form of hardware or architectural limitation, a fixed bug, some performance hi-jinks or a curious customer requirement.
Oh I also use them to explain to readers that i've considered certain code paths and am happy they do nothing.
if(blah)
{
blahblah
}
else if(blah)
{
blahblah
}
else
{
// do nothing
}
Well, I partly agree... and then I disagree again. First of all
COMMENTS ARE GOOD!
Never think otherwise. Trying to avoid comments is a step into the wrong direction. It's not about avoiding comments. It's about getting your comments RIGHT(tm).
As other people pointed out, by choosing the right name for the function, you made clear, that this function calculates a square root. But you don't tell people which method it uses and why you chose this method.
This gets me to the point:
1) Don't use comments to tell people what you are doing, unless it is very hard to see that by just looking at the code. Always assume that whoever will read your code is a good programmer and knows the language your code is written in quite well.
Most useless comment I have ever seen:
// Increase i by one
i++;
<sarcasm>Wow, thanks for the comment. Without it I had never guessed what happens there!</sarcasm>
If somebody needs a comment to know what i++ does, he shouldn't be reading this code in the first place.
But your square root example is a good example where I would leave the comment, even if you chose the function name to be more obvious, the name does not reflect which method you use for calculating the square root. I had at least written that as
private double SquareRootApproximation(n) {
// Using Newton-Raphson approximation
...
2) Always use comments to tell people WHY you are doing something.
The "what" might be obvious by just looking at the code, the "why" certainly never is. How can it be? The why exists only in your head. It's a design decision you made while writing the code and maybe not even you yourself will know 3 years later why you made it that way and not any other way. So make sure the "why" is either always obvious (because it's trivial) or add a comment that explains your design decision.
3) Don't over-comment.
I guess that was your main critics here and I totally agree with you. A lot of code has more comments than actually code. If that happens, something is wrong. It's highly unlikely that 100 lines of code are so complicated, that they need 300 lines of comment to understand them.
If you really implemented something so ingenious, that you want to share your cleverness with the whole world, write a 50 pages PDF file, upload it somewhere on the web, add a two line comment to your code that contains a link to it. Who really cares for a long winded explanation of what this code does, why it is so cool, a proof that it really works, a performance comparison, and so on, can grab that PDF and read it. For the rest of us, just add a comment what the code does, why you decided to do it that way and that it is really great - we will believe you ;)
Mecki on July 25, 2008 02:27 AMWhilst I don't like essays as comments I still think adding that one line tidbit you'd added is useful.
// square root of n with Newton-Raphson approximation
Don't get me wrong, I'd still probably stick it as some sort of static method in a utility class somewhere but I like to know a little about the logic being used, and I think it becomes more relevant with more complex examples.
As an example this week I was working on some code to calculate the distance between spherical coordinates (lat, long), for my purposes I decide that the haversine formula - with a rough error of 3m for every km - was suitable. To me putting in something like
// haversine formula - error margin 3m per km
makes sense. Any other developer would be able to see it's limitations and determine if this was suitable for their needs.
MarkM on July 25, 2008 02:37 AMHoly crap, is this bizarro world? Programmers are writing TOO many comments? I've never heard such a thing! I wish this was in line with my experience.
Just because I am a programmer and I can read code, does not mean I should have to. I'm not a compiler. Sure, I completely, 100% agree that code should be self-documenting where ever possible. On the outskirts of code, you will likely have some type of controlling logic which creates objects and calls functions, all of which should be fairly self-documenting and the flow is obvious and beautiful. These are the trivial cases. But as you get deeper in the meat and potatoes of the code, it becomes harder and harder to understand the code as immediately as the trivial parts. Instead of reading the code like a book, you have to start parsing the code like a compiler. It's inevitable. Not everything can be broken into a 4-line function with a nice name. In these cases, a simple "// XX does YY and then ZZ" makes all of the difference in readability. Not only that, but it shows the programmer's intent. If there happens to be a bug in this area, I can identify what the programmer was _trying_ to do, why her assumptions were wrong, and thus fix the bug. Self-documenting code is completely worthless if it's inadvertently documenting the wrong thing.
Really, the issue here, is the maintenance phase of the programming life cycle. As we know (From Facts and Fallacies), the maintenance phase consumes 40-80% of the total costs of a project. And maintenance programmers spend 50-60% of their time deciphering the code they are maintaining (Code Complete, referencing another source). So the question is, do comments help this "deciphering" phase? Yes. They do. They help more than not having them, that's for sure! I'd rather have too many comments than not enough. I think it's plainly obvious, but I'm sure there are studies that support it. Here is one with a few seconds of google searching: hxxp://csdl2.computer.org/persagen/DLAbsToc.jsp?resourcePath=/dl/trans/ts/&toc=comp/trans/ts/1988/09/e9toc.xml&DOI=10.1109/32.6171
Any time you have code that is going to need published documentation, JavaDoc-esque systems do take a lot of space comment-wise, but if you need to maintain documentation anyways, it's easier to do it right there in the code. It just takes a bit of discipline to remember to update the doc block if necessary whenever you are doing something in the code. Much more convenient than maintaining documentation elsewhere. And it may be useful to other programmers looking at the code, too.
It seems like there are a lot of posts on this blog and associated blogs with the tone of: "<Generally accepted good thing here> is actually TERRIBLE!!! OMG!!!". This is reminiscent of cable news network scare tactics and nonsense to start controversy when there really shouldn't be any. Yes, using comments, design patterns, regular expressions, XML, etc to the _extreme_ is bad. Of course. This could be said about anything. But what should be known is that they are generally _good things_, but should be used correctly, with care, and under the appropriate circumstances. Self documenting code and comments are both things a programmer should use and continually attempt to get better at.
Preaching the correct way to use these things is probably going to be much more helpful for those you are trying to address. I see that you aren't saying all comments are bad- But that is certainly the tone. It's not until the last sentence that you admit there may be a use for them. I think people like you, Sammy, and others currently on an anti-comment binge are only going to hurt yourselves if you are so strict and unwavering in regards to code commenting.
The effort it takes to write them is _vastly_ (and I mean VASTLY) overstated and the space it takes up on your screen an irrelevancy, as far as I'm concerned (Ignore the dark-green text!). You act like a programmer needs to be a novelist to write simple comments. I think I've seen people have a harder time naming functions appropriately.
In short, I don't think you are young enough to be so idealistic :)
SB on July 25, 2008 02:39 AMIt's not possible to overcomment something in reality.
This is another one of those bull$hit macho, 'I don't need comments in MY code' threads that should become ignored.
Jeff, why don't you go and re-read one of your favourite books, the Mythical Man Month, to hear all about this discussion and why you are wrong?
Paul Hollingworth on July 25, 2008 02:45 AMAnother related issue is use your source code control and don't use comments as a kind of historical record of code that has been replaced. It works for a couple of iterations in case your refactoring broke something - maybe - but 20 iterations later it's plain dangerous.
Be brave, delete stuff and trust in your source code control system.
Francis Fish on July 25, 2008 02:55 AMBut I like telling myself stories as I wrote code! Honestly, the layman's-terms expression of the function of whatever I happen to be developing is actually helpful, I've found, in keeping my own thoughts straight. So while I might have 4 times as many comments as you might recommend, I feel like my development process has been smoother and less convoluted. It probably helps solidify new concepts too.
However, before I hand my code over to another developer, or particularly before I deliver it, I strip out all my 'note to self' comments and rewrite things a lot more sparsely. It's kind of redundant, I know, but it works for me, so I figured it'd be worth mentioning.
matt on July 25, 2008 03:04 AMWhat about when you're in a real world situation and you've just got to make a deadline? You can't begin to refactor your code for ten times, you've just got to get that shit out of the door.
J on July 25, 2008 03:06 AMbool comment = false; // indicates whether this comment is required
Steven Bey on July 25, 2008 03:12 AMSeems to me that everyone who is advocating writing comments in code are doing so from a point of view that code is difficult to understand.
My view, is that if well written (and that is important) code is hard to understand then it needs a comment. But if bad code is hard to understand it needs to be refractor.
And refactor is not the same rewriting (as it seems a lot of people seem to think). Refactoring implies 'no change in functionality' and therefore should have the same regression testing requirements as "slapping on a comment" (which is after all still a change to the source file).
Commenting badly written code (instead of refactoring it and correcting the 'badness') just propagates the problem further down the line to another person who will have to read both the comment and the code later.
Ron on July 25, 2008 03:17 AM<Self-documenting code is completely worthless if it's inadvertently documenting the wrong thing>
Self-documenting is by definition the right thing. It may be poor code and wrong, but it is the correct documentation.
Comments rapidly become out of date with refactoring, and with fellow programmers not updating it.
// Newton Raphson method
private double SquareRootApproximation(n) {
(some other algorithm)
...
}
Writing tests before code documents the requirements by defining the inputs and outputs. No code comments required.
Also, why are you reading the code if you don't know why or how you got there? Junping into the middle of a program without an aim is pretty pointless.
Aaronrs on July 25, 2008 03:20 AMthis post reminds me of the NeHe OpenGL tutorials, where every single line, including opening and closing braces are commented.
Comments in my code are just that - comments; little side notes, kind of what you'd note down next to someone else's code if you were tring to work out what it did.
And if you hate giant comment blocks, don't view source that's been formatted for Doxygen.
James on July 25, 2008 03:29 AMIf you're doing Newton-Raphson, I hope you're doing so for a reason other than demonstrating your Mighty Math Muscle. State that you're using this algorithm, and why. State the accuracy bounds, and enforce via tests. Don't leak implementation detail in the interface.
Jeff's "SquareRootApproximation(n, Type.NewtonRaphson)" examle is bad for reasons already mentioned, it's clunky, and depending on language+compiler might generate suboptimal code. If you're doing N-R it's usually because of speed concerns, so you don't want suboptimal.
I do fully agree you shouldn't comment every single line, though, and maintenance coders not updating comments *can* be a problem. But would you want a maintenance coder on your team who changes algorithm without updating comments? Chances are that coder won't be writing proper tests, either.
As for "Junping into the middle of a program without an aim is pretty pointless." - debugging other people's code, perhaps? :)
f0dder on July 25, 2008 03:31 AMIt's reassuring to read the replies and find that so many people don't buy the "less comments are good" nonsense.
There are two main reasons that lead to this incorrect thinking:
1. Developers think that code tells you "what" is being done and comments should tell you "why" it's being done. This is nonsense. Code tells you "how" something is being done, and comments should tell you "what" is being done on a semantically richer level than instructions intended for a machine. Even better if they also tell you the "why".
2. Developers regularly overestimate the self-explanatory power of code they have written themselves. It's only experience that teaches them to take nothing for granted. Please don't tell inexperienced programmers that comments should be avoided.
I agree, however, that writing good comments requires good writing skills that many coders do not possess. Again, it doesn't help to reassure these that comment-free code is good, because without practice, they never gain the necessary skills. In my opinion, comments and code intimately belong together and should be improved together.
By the way, I think that programming skills correspond with writing skills on a very general level. Bad writers confuse ideas, present them incoherently, get character traits wrong, use inconsistent naming, grammar and punctuation, and tell their stories in an unimaginative, boring and sloppy way, not detecting mistakes and limiting story development through these errors. Bad coders confuse and misunderstand requirements, structure code incoherently, get abstraction levels and data structures wrong, use inconsistent naming, idioms and punctuation, and sloppily implement algorithms that are unimaginative, inefficient and buggy, limiting maintenance and enhancement possibilities. I believe that good programmers are mostly good writers and vice versa. As a corollary: Most software is buggy, inefficient and hard to maintain because their authors suck at writing.
You could go a long way in telling people how to write and code correctly, Jeff, and improve their coding abilities. For my part I'd look forward to again read an inspiring post from you. It's about time.
Apprentice: either writes comments, lots of comments or writes incomprehensible code with no comments.
Journeyman: writes self-documenting code with no comments.
Master: Writes comprehensible code that is commented where doing so enhances understanding.
Something like that?
Mike Woodhouse on July 25, 2008 03:36 AM> For my part I'd look forward to again read an inspiring post from you
Do I really need to write a post saying "comments are good, please use them?" That's like writing "code is good, please write it."
http://www.codinghorror.com/blog/archives/000878.html
If the best code is no code, what is the best comment?
> Apprentice: either writes comments, lots of comments or writes incomprehensible code with no comments.
> Journeyman: writes self-documenting code with no comments.
> Master: Writes comprehensible code that is commented where doing so enhances understanding.
+1
Jeff Atwood on July 25, 2008 03:44 AMCouldn't agree more about the thrust: comments should be used sparely, and code should document when at all possible.
But let's face it -- anyone replying to this post is part of the 5% of programmers who actually give some thought to the topic while working.
It's the other 95% that's the problem.
John Pirie on July 25, 2008 03:46 AMWhat the hell???
Instead of adding a single line of comment, you recommend writing the stuff as a function/method, and comment it by giving this function a speaking name - even though the code is onl run once, and no function is necessary(otherwise it would be there anyway)?!
Sorry, that's not real affective, and will, for all those morons that make other developer's day hard by not being able to give functions a decent name, not make anything better.
And then the "You should always write your code as if comments didn't exist.".
Totally mislead - as when you're walking along the equator to find th north pole (not as wrong a s on the south pole, but here, not even the temperature is right...)
I code by writing the comments first - saying in human language, what I'm actually about to do, and, by that way, realizing problems in things because I have problems to describe them - so, before the first line of actual code is written, I realize problems in my spec(if such thing ever exists - in real life you don't get these so easily).
When I write unit tests, the first thing I do is try to write "prerequisites" and "expectations" into the comment above the code - before starting to write the test. As with the coding itself, it makes me reassure, that I have enough inside in the problem to be solved so I can describe it in a short sentence - if I'm lacking this, I will never be able to write a decent line of code doing these things.
Even though I don't want to force that style of working to others, I feel it's working great for me - it leads to well thought out coding, and can _never_ lead to undocumented code.
However others work - what you describe and recommend here is nothing else to me but the title of this website...
The solution, of course, is to use the "Commentator":
http://www.cenqua.com/commentator/
Oops, wrong URL - get me here: http://lazyb0y.blogspot.com
Henning on July 25, 2008 04:32 AMI suppose the level of detail in comments depends on the level of understanding by the people looking at the code; where I work, not all 'programmer' are at the same level (I wouldn't even consider some of them programmers at all) so whenever I loop through an array I have to write down what's happening otherwise I get people ringin me up asking me what's going on.
silence on July 25, 2008 04:44 AMJeff,
I couldn't agree with you more. In fact, I wrote a very similar post 7 days ago about the exact same thing (shameless plug: http://tinyurl.com/6m8tsl). I think my language was a bit stronger against comments, but your language was clearly more articulate.
Brian Genisio on July 25, 2008 05:01 AMJeff,
>Do I really need to write a post saying "comments are good, please use them?" That's like writing "code is good, please write it."
No. Make people reflect. Let them benefit from your experience. Show them the "how", not the "what", and let them draw the conclusions on their own. Put things into perspective, rather than advocating one side. You've got an audience, so you've got responsibility.
>If the best code is no code, what is the best comment?
Well, if the best code is no code, then the best job is no job. Ex falso quodlibet ;-)
Sure, I agree that less is (sometimes) more. But you also know that there's a limit to "quality by reduction". Why shouldn't the same be true for comments?
Leo on July 25, 2008 05:06 AMyou are a shameless flame-baiter
structure on July 25, 2008 05:14 AMAnother excellent compromise that you skipped, is meaningful variable names! I am not familiar with Newton's Method (might have seen it in school, *coughcough* years ago), but it looks like r is the root and t is a tolerance. Why not call them that? "while ( abs( root - (n/root) ) > tolerance )" would have been clear enough that I could figure out at a glance what that was trying to achieve.
Dave Aronson on July 25, 2008 05:16 AMHarrumph. I *did* check to see if anyone had already commented on the var names, but for some reason the web site only showed me the comments written up to Dan's of 08:09 PM last night. Methinks there's a naughty cacher somewhere on my slow link. Sorry! B-(
Dave Aronson on July 25, 2008 05:20 AMJeff:
Comments are for the next guy who has to modify the code at 3 am when production is down and the original programmer has moved on. As a maintenance programmer for several decades, I can tell you that novel like comments do not help. But single letter variables that you used in your example do not help either. You are making the assumption that the next guy in line will know what you know the instant you are writing that line of code. (That next guy could be you 6 months later and at 3am all math is fuzzy logic.) There are coders and there are programmers. Programmers don't ASS-U-ME!!!
private double SquareRootApproximation(square) {
rootApproximation = square / 2;
while ( abs( rootApproximation - (square / rootApproximation) ) > tolerance ) {
rootApproximation = 0.5 * ( rootApproximation + (square / rootApproximation) );
}
return rootApproximation;
}
System.out.println( "r = " + SquareRootApproximation(r) );
Jeff, I have lost the last little bit of respect I had for you with this post. :P
Seriously, though, I do find short "what are we trying to accomplish here" header comments helpful. Note that your refactored example no longer conveys the fact that it's doing a Newton-Raphson approximation. Maybe that's not a big deal there, but there are other situations where a fact like that would be good to know.
I like the goal of code blocks to be commented, so "what" in the sense of "what are we trying to accomplish" instead of "what are we doing" (which you correctly say should usually be understandable from the code itself).
Bob on July 25, 2008 05:31 AMReminds me of one of our junior developers here. Her manager told her to comment a lot, so she does things like:
//Get the http session.
HttpSession session = request.getSession();
Which is utterly useless and just clutters the source files.
a on July 25, 2008 05:34 AM@Will:
You just beat me to it.
Good method naming is great for people calling your code. For people actually maintaining your code, all naming is important. Method, variable, class, etc names should all be descriptive.
If there isn't a clear name for an entity, there's a very good chance that it shouldn't exist in the first place.
One good example is loop counters. How many times have you seen "for(int i = 0; i < some_number; i++)", when there is actually a meaning to the loop counter, such as an array index, or something_count?
By all means, keep code terse, but not to the point of obfuscation. FFS, a couple bytes of extra code for clarity is great value.
Chris on July 25, 2008 05:41 AMtry writing some readable assembler code without comments... good luck with that. :)
good post. i am often guilty of explaining in too much detail how something works in comments, whilst leaving other things uncommented altogether when they really need a good comment...
jheriko on July 25, 2008 05:46 AMI still put some comments in my code, but I do make my code descriptive. The comments are typically for me, as more of a reminder of what I was wanting to do when I start to stud out a new class or method. I'm starting to do that with the TODO comments, but learning how to code w/out having that option available, I just got in the habit of one line comments as a quick reminder to myself of what else I needed to to do.
mjmcinto on July 25, 2008 05:52 AMI agree with Will. I have personally been in the situation where I was asked to add a feature to a program that I had written three years earlier. I *thought* I had a good idea in my head as to how the original source code ran, and foolishly answered that it would be easy. I had a pretty good idea how to do it. But then when I looked at the actual code (with no comments, and with variables named 'x' and 'y' etc.) it took much longer than I had predicted just to find the right place to modify the code. FWIW, once I figured out *where* to modify the code, the actual modification was as easy as I thought. If only I hadn't used up more than my allotted time for making the modification just figuring out my own code. BTW, this wasn't even at 3 AM.
Pete S on July 25, 2008 05:53 AMI have worked on teams where EVERY new line you write needs to have a comment (and the version control nazi/supervisor would nag you to death if you didn't). That certainly doesn't help anyone. If I write a function called "ClientAuthNumber(client_id)" I don't think I should need to add "// returns client authorization number based on client id" or "a = b + c; // a equals the sum of b & c" ...but I guess there are those who disagree.
On the other hand (and just as important), my team is now working on a huge application written by another company which we have to manage and there is hardly a line of code on anything. It seems for about a 2 year period from 2005-2007, they usually added just who updated it and when...not why it was added or if it affects anything else.
IMO, there is nothing harder to read than code that has 2 lines of comments before every line of code. If it is that hard to understand without EXCESS commenting, maybe it wasn't well-written to begin with...
bob on July 25, 2008 05:59 AMWow, Jeff is really on a roll here. Code and comments are bad!
I guess I never realized that Coding Horror was actually about coding badly. Comments are not bad, *BAD* comments are bad. Just like code isn't bad, but bad code is bad.
I'm honestly having a hard time believing someone as supposedly intelligent as Jeff actually believes this crap. It looks to me as though Jeff has discovered if you post controversial stuff you'll get more ad hits. Whatever, thats his prerogative but I'm not reading it anymore.
Matt Newman on July 25, 2008 06:08 AMComments are my friend. Sure I could write a big block of code and walk through it to see what is done, but isn't it quicker to just read a sentence or two before it so that I know what it does?
In addition, if you code something wrong (not that I would do that, but maybe some other developer would), wouldn't it be nice to have a comment that says what the code SHOULD do?
My favorite comment is when someone does this...
x = 2 // set variable x to 2.
Not that I'd ever use that, but it makes me laugh when I see it. And then die a little inside.
Kris on July 25, 2008 06:09 AMI totally agree with the article.
Luigi R. Viggiano on July 25, 2008 06:16 AMAs I think one or two others may have pointed out (rather verbosely, haha), I also use comments fairly often to document design decisions.
My present example is a checkpoint system for realtime data, the logistics of which make my head spin. So there are little hints peppered around the provider class that explain, for example, why the end date of some checkpoint is not the same as the end date of its corresponding transaction. Or why the "original" and "modified" parameters are swapped in a certain call (I can just imagine someone reading the code, assuming that was a mistake, and proceeding to break one of the most critical components).
Of course, most of my smaller projects have no comments at all - they're simply not complex enough to require them. There aren't really any significant "design" decisions.
Actually, Jeff, in this case, I think both the original example and your "refactored" version are wrong. There should be a comment, but not the comment that's there. The comment should answer the question: why are we using a hand-rolled square-root-approximation function when there's already a perfectly good sqrt function in the math library?
Aaron G on July 25, 2008 06:24 AMAlex: I think you're correct for the first time through the loop, but after that it changes and converges on the result.
mike on July 25, 2008 06:32 AMOne of the most important things I use comments for is to explain what is not available from looking at the code. For example a requirement of a called procedure:
if (x < 0) then AbortProgram("X is negative");
y := PerformSomeMagic(x);
May deserve the comment:
//PerformSomeMagic will give incorrect results if passed a negative parameter.
I think Jeff has made his point by using an over-the-top comment example. I also comment methods before writing them. But I'm a bit more succinct about it (VERA code in a HW verification test bench):
// After (possibly a series of) call(s) to
// set_field, this task is called to write
// the shadow_value to the physical DUT CSR.
virtual task commit_fields_t(integer access_method = CSR_DEFAULT_ACCESS);
In my last post, http://mjbiren.blogspot.com/2008/07/check-in-your-changes.html, I note that one of the things you need to do when checking in changes is to make sure the comments are still relevant. This becomes easier if the comment's content is short and only about code intent. Code details always change, if you comment like you're writing code - then changes always become twice as much work.
So in the end, I think I half agree with Jeff.
No use of regions in you code, no comments, what's next? Shall we say no to line breaks. Visual Basic you need them, but C#? It's just a waste of space not to be using every pixel of your screen for conveying information. Why should I have to use my mouse wheel to scroll up and down someone else's code when they could have fitted it into one small area. This would allow me to have many classes open on my screen without having to alt-tab between them. So efficient is this way of code that before reading any code I run a script to remove all white space from it and check it back in. Another advantage to this style of coding; I can use a USB photo frame for displaying some of favorite classes of code. Code Analysis can now include looking for secret "Da Vinci Code" messages. The fate of the world is in your hands if only you would advocate proper coding standards. Come on Scott the world needs just one more controversial coding practice to save it.
Dave on July 25, 2008 06:45 AMIn a perfect world our comments would write the code.
Practicality on July 25, 2008 06:45 AMAnd then your subroutine fails because t is undefined.
dnm on July 25, 2008 06:55 AMI dunno, I would still appreciate a one-liner about which approximation algorithm was being used. Numerical methods isn't my strong point.
(@Will: The use of short variable names in the refactored function is fine; it's a math algorithm and you need to be familiar with the algorithm to get it anyway; the long variable names doesn't help there.)
Adam Vandenberg on July 25, 2008 07:02 AMHow to dupe the world into thinking you are an Authority: Write lots of opinionated, loud blog posts on lots of subjects. It's fast becoming clear that Jeff Atwood is not a skilled developer. In fact, as you watch his writing about stack overflow, it becomes very clear that he is flying by the seat of his pants and has no idea what he is doing. He even admits that he has some sort of pathological need for public attention in the last podcast. Sure, it's entertaining, in a train wreck sort of way, but I sure feel sorry for people who come here thinking they are getting good advice and that Atwood knows what he is talking about.
Jon on July 25, 2008 07:02 AMIn our organization (or the part I'm in, anyway), good practices like commenting code have not been paramount. I'm working to change that, including a requirement in the group I lead that we comment our code. It doesn't (and shouldn't) be book length, but some helpful hints here and there, telling "the next guy" what was intended, is very helpful.
Scott Marlowe on July 25, 2008 07:02 AMComments are an invaluable tool designed to communicate what is otherwise incomprehensible. If I come behind you, I'll be cranky because I have no idea what the "Newton-Raphson approximation", and you didn't bother to make a comment on the subject.
Sometimes we have to write highly complex code, and comments are a way to help understand those tough blocks, but the real power of comments and where they shine is communicating business concepts. After all, it's our job to help the business move forward, so that is where we have to focus our understanding.
Just my two cents.
Corey Furman on July 25, 2008 07:05 AMI had a college professor who loved to kill us with documentation - his favorite example was "How zero's do you see? 000000000" and then he showed us "000|000|000"
The professor said: "See - I added more stuff and it's more readable!"
Years later - I realized you could use whitespace and change it this to get the same result: 000 000 000
Sometimes less is more.
Yep, must agree with the majority of posters here and disagree with Jeff. I start with comments as I set the architecture in place and then flesh it out with code. Yes, the comments typically stay in some form. And if you wanted your function (which I wouldn't make something a function just to avoid a comment block), then it would require more work (which I would argue it needed anyway)...
// Newton-Raphson approximation
private double SquareRootApproximation(iRoot) {
fRootApproximation = iRoot / 2;
while (abs(fRootApproximation - (iRoot / fRootApproximation )) > iTolerance) {
fRootApproximation = 0.5 * (fRootApproximation + (iRoot/ fRootApproximation));
}
return fRootApproximation;
}
System.out.println( "Root Approximation = " + SquareRootApproximation(iRoot) );
Phil on July 25, 2008 07:13 AMI would have to agree that self-commenting variable names and function names area always more valuable.
As far as the other comments, my commenting style is constantly changing. Sometimes more, sometimes less. I nearly always think what I am currently doing is the best. I am sorry to say, but I think there are pluses and minuses to both. Assets and liabilities.
It's actually just a preference. Seriously (as long as your code is actually easy to read).
Practicality on July 25, 2008 07:22 AMIn Russia, comments write *you*.
B0R1S on July 25, 2008 07:26 AMMost of my work is cleaning up and maintaining existing code. Usually the original developer was a newbie, the code is hard to read and comments would make my life a lot easier. However, if the code was written by someone who knew what they were doing it's usually obvious what is going on and comments are already in places where it makes sense to have a comment. I think the longer a developer codes, the more he/she learns to write "self-documenting" code and when/where to add a comment.
PaulG. on July 25, 2008 07:30 AM> Junior developers rely on comments to tell the story when they should be relying on the code to tell the story.
I disagree. Comments are the context which code itself might not provide. Normal human reasoning does not always align with code architecture; this is why we consider a meaningful understanding of design patterns to be one sign of maturity (i.e., they take effort to internalize). Just as a graphical interface needs both a usable design and helpful documentation, so does code. This is because none of us are savant designers, capable of providing fully-comprehensible designs (to all audiences, locales, and experience levels!).
That's my "big picture" response.
On the pragmatic side, engineers in any rapidly-changing field will need to frequently migrate between languages, platforms, and goals. While we should all have a firm grasp of programming fundamentals, the reality is that we often need to modify code we're not seasoned veterans of.
If you have the luxury (or curse?) to work in one language for your entire career, then comments may seem superfluous. But throw in either a complex architectural solution (e.g., for performance or enterprise integration purposes), or new languages and libraries, and all-of-a-sudden a few comments here and there significantly improve task completion times.
Everyone benefits from comments -- junior and senior engineers alike.
Vance Vagell on July 25, 2008 07:37 AM"You should always write your code as if comments didn't exist."
I agree to the fullest, although I find it hilarious that you can say this in the midst of using single-letter variable names.
Josh Stodola on July 25, 2008 07:40 AM// Constant Comment is a pretty good tea.
Charles on July 25, 2008 07:44 AMJust... whatever you do... don't add regions!!!
/had to
Ivan on July 25, 2008 07:44 AMThe best comments are like:
// Increment i
i++;
"While comments are neither inherently good or bad, they are frequently used as a crutch. You should always write your code as if comments didn't exist. This forces you to write your code in the simplest, plainest, most self-documenting way you can humanly come up with."
Disagree. Comments exist for a reason, we should make use of them, not write code that doesn't need comments. Its not like comments are included in the compiled code. Shit most editors, make comments a different colour, you can easily ignore them. You know your blogs bug me. You moan about everything, php, xml are ones that stick out in my memory. Maybe you are an old school programmer who doesn't like the new breed. But i'm afraid we are in a field where what's new is old before it hits the mainstream. You need to adapt man!
Back to your comments hissyfit, I try to write efficient code ie use less memory, less cpu time etc... This some times leads to the code being hard to understand, no matter who is looking at it. Yea i try to keep it simple and plain, but sometimes to get that speed plain and simple doesn't work. So comments come in, not on every line, hell no, but a little summary saying what the method does is quite fine.
Mitch on July 25, 2008 07:50 AMAs stated above by several others, my most common use of comments is for business logic. As the majority of applications I work on are complex applications with obscure business rules, leaving comments definitely helps future developers on the project.
David Parker on July 25, 2008 07:54 AMThe argument that
SquareRootApproximation(n, Type.NewtonRaphson)
is more readable than
// Uses Newton Raphson
private double SquareRootApproximation(n)
is pretty weak. I'd rather see a comment here than the first one. While I think you do have a good point about bad comments, please try to find a better example before you make your point. The current example is terrible because it does need at least one comment to be completely readable and easy to maintain and therefore, weakens your point considerably.
Cecil on July 25, 2008 07:56 AMAt school, the only thing the profs teach in the first 8 weeks is commenting. In my first year the teacher would knock points off every program we wrote, if there wasn't at least one comment for every line of code.
Chaise on July 25, 2008 07:56 AMI like comments as easter eggs -- my last day at a job I added a joke to a colleague as a comment. Three months later I got a nice call from him :)
paul on July 25, 2008 07:59 AM
Scott please bring some perspective to you blog entries, you make some valid points but why do you see the need to make everything so extreme?
I promise to carry on reading but I would prefer a more balanced discussion. I appreciate this is YOUR blog, but as you have clearly positioned yourself as a semiprofessional blogger, I'm not sure it is becoming of you to be so myopic.
Joe on July 25, 2008 08:04 AMI think the one point developers should take out of this is the bolded note "You should always write your code as if comments didn't exist." It's probably one of the hardest tasks in our world and for those of you against self-describing, simple code, shame on you. There is enough complexity in the systems we produce that it makes little sense to have it at the functional level.
I am often guilty of poorly name variables (love the 1-, 2-, and 3-letter names...) but I often find myself going back and renaming them later. My past excuses for short names has since been trumped by Intellisense -- less time is compromised by "typing" long names as the IDE does it for me now.
I've had one "what-the-heck" moment with some critiqued code. The first was with a continue statement in C++. "You should put a comment in there to say what 'continue' does." My confused reply -- "You want me to explain a keyword of the language?"
The last comment as I'm typing this is "In a perfect world our comments would write the code." I like the implications of it -- imagine a world where people used proper grammar and spelled words correctly...
Great article Jeff!
Austin on July 25, 2008 08:06 AMSome sniglets for you:
Obso-doc: Comment detailing what the code did last year.
Redundo-doc: Comment literally describing source code statement(s).
Histo-doc: Ever-increasing comment section detailing revision history, typically duplicating information in Revision Control.
Igno-doc: Comment revealing author's lack-of-understanding of necessary algorithms, alternate syntax, etc.
Personally, I believe in minimal commenting in-code (doesn't count "Javadoc" documentation, which I don't consider comments) only to warn subsequent visitors (like me during maintenance) about certain code sections that are arranged a certain "atypical" way on purpose, i.e. to workaround something somewhere else. I prefix these with "IST" for Important Safety Tip! This heads off the "What the F*** was he doing here?" impulse to just rip it out and re-do it the "right" way.
The Gassy One on July 25, 2008 08:28 AMMy extended thoughts on this (in addition to comments posted above):
http://www.krissteele.net/blogdetails.aspx?id=70
Kris on July 25, 2008 08:33 AMNot a fan of literate programming then?
http://www.literateprogramming.com
Personally, I think Knuth is on to something very valuable.
Like you, I really appreciate self-documenting code, but there are times when comments are absolutely essential for the next developer.
Your post can too easily be misconstrued; and, if there is one extreme that I have come across all too often it is the absence of comments.
Jeff, have you ever worked as a maintenance developer on a large application?
Jo on July 25, 2008 08:37 AMI prefer to start with comments and fill in the code. This leads to good comments and good code. Once the code is working, I might prune/edit the comments that are redundant.
Giant template-driven comment blocks at the tops of files and before each function are useless.
One of my pet peeves is when people comment the interfaces with implementation details, and the implementation details with instructions for use. If you're in C++, where prototypes are often separated from implementations, it's good to think about the appropriate comments for each context. People looking at the prototypes are trying to figure out what your function does and how to use it. Developers looking into your implementation need to understand how it works and why you made certain decisions.
The commentless Newton-Raphson example could still be improved with a comment that says "Newton-Raphson". At least that's something someone unfamiliar with the algorithm can search on.
Adrian on July 25, 2008 08:39 AMGood timing. I was just hired to add a video snippet of code into someone else's website. The previous developer most have thought it was cool to reformat all of the code into one single line with no spaces or comments. It's a mix of bad ASP and HTML. So now I believe the previous guy knew he sucked and just wanted the code to be difficult to edit by the business owner.
So the ethics question is should I just insert my properly coded, commented, indented and extra white lines of code into the other guy's jumble of mess? Or should I spend the extra time on the previous developer's code and force line breaks at all of the right spots, create indentions at all of the right nestings and add comments as to what I think he meant to do???
Well this client happens to be my friend on my weekend soccer team and I think I'll extend the courtesy to clean the entire page.
My take on comments...
I give my clients the "If I die" speech each time I run a project where they are given complete access to all source code, source images and help files for easy transferance to any other programmer. And within the source code there is just enough comments to help a decent programmer. And within the source images, there are just enough comments on each layer to help a decent designer. When I mean decent, I mean that the comments are not too long or descriptive to help a non-programming business owner think that they themselves could attempt to make code changes. (dangerous).
Paullee on July 25, 2008 08:46 AMI always heavily comment my code. It's not just for people to follow behind me. No. Its because 2 weeks later I'm knee-deep into something totally different and when I return to the previous code I need a gentle reminder.
As far as not having comments in your code, couldn't you use a comment stripper as part of your automated build process?
Ian Patrick Hughes on July 25, 2008 09:01 AMHere is another one:
Identi-doc: Author tediously annotates each modification with their date/initials.
I don't know how many times I've seen this! Please everyone give that one up.
The Gassy One on July 25, 2008 09:01 AMHeh, aren't function names themselves an abstraction designed to succinctly describe a block of code to programmers, just like comments? I mean, computers don't really care if you call it "SquareRootApproximation", "foo" or 0x00401000.
Saying comments are bad is like saying coding is bad. There are intelligent and stupid ways of doing everything.
Also, C#'s /// syntax is arguably superior if you want to add descriptions to the autocompleter or to API docs. You can't make function