How to Write Comments
Denis Krukovsky writes "Should I write comments? What is a good comment? Is it possible to comment a class in 5 minutes? See "
Everybody knows that good code is self documenting- which is why my prof in college demanded we write in Ada. I instead suggest commenting in haiku.
Code should read easy Like many Slashdot comments See? It's not so hard.
ACs are modded -6. I don't read you, I don't mod you, I don't see you. Don't like it? Don't be a coward.
<!-- why don't they ever RTFA? -->
<b>Nothing for you to see here. Please move along.</b>
liqbase
There was a final project worth 50% of our final grade (it took 3 months todo) I didn't comment and I fail it.
Actually, that would give some of us that have to review code something interesting to look at. Those that think code is self-commenting, forget that there are people like me, who aren't great programmers, who have to either fix your bugs, make simple modifications, or add really simple things. When there aren't comments, it is hard to figure out what parts of what do which.
Zhrodague.net - I do projects and stuff too.
Asking Slashdot "Should I post comments?" is a bit like asking turkey's "Should we cancel Christmas?".
Let the commencement of the comment posting beginulate!
Simple, and I've posted this link a few times before, but you really need to use cenqua. Takes all the pain out of comments, and still allows personality quirks to show thru.
The Commentator
Just be careful on your settings and you should be fine.
Don't blame me, I voted for Kodos
Rob Pike, a former powergeek at ATT&T labs, and a present powergeek at Google, has the following to say about code commenting. In general, I agree with him.
Just like good documents are self coding...
If I could, I'd destroy you all.
I know a lot of people say comments are unnecessary if you have nice self-documenting code. But personally I find nothing beats a short comment at the top of chunks of code to give a quick idea what it's doing (or supposed to do).
I once read that a good comment will appear on every conditional branch or loop, and a good comment will also state the INTENTION for doing something, rather than what is actually being done (because the programmer can usually figure out what is being done). For example: // i starts at 1 instead of 0 because we don't want to process the application's name (first argument) // AND with 0xFF1234 because that is the first set of bytes in the file header // say file not found instead of invalid due to reason blah blah blah ...
for (int i = 1; i argc; i++)
{
printf("ARgument is %s\n", argv[i]);
}
if (u & 0xFF1234)
{
printf("File is valid.\n");
}
else
{
printf("File not found.\n");
}
guide here
Covered here
Oh... you meant code comments... never mind!
My pics.
It's like C++ with some thought to design...
Who is Denis Krukovsky, and why should I (or anyone) care what he says?
I did RTFA: it was poorly written and makes some statements that most people would STRONGLY disagree with. For instance:
The point to start writing comments is... when the code is ready to be presented for others.
Sure my code is readable, but more often than not I find my comments explaining the screwed up business logic behind the code.
A comment should tell you why something is in place rather than what the code is doing:
// Check tarriff is null
...
// 30-11-2005 Fixes a null reference exception that occurs later on if no reference is available.
...
A trival example:
Don't do this:
public bool CheckSmsValue(Account smsAccount)
{
if (Account.Tarrif == null)
return;
}
Do do this:
public bool CheckSmsValue(Account smsAccount)
{
if (Account.Tarrif == null)
return;
}
Simon.
this block for mailing
checks addresses for error
errors on failure
*bow*
During college I always lived by:
"It was hard to write; it should be hard to read"
'course the profs didn't appreciate that much...
You should use Java instead (or another easily readable and understandable programming language). Ok there may be some cases where a comment is needed but it is quite rare. Give the source, that should be enough. Of course, if your design is complex, you should write design/technical documentation (but it is out of the scope of comments anyway). Don't hide important information into comments, give it its own status. Don't clutter your code with comments. IMHO.
Million Dollar Screenshot
/* you are not expected to understand this */
No folly is more costly than the folly of intolerant idealism. - Winston Churchill
Try your best to make your code unreadable by anyone else other than you. That will keep you employed :P
The code can tell me what it is doing, but it can't tell me what it is supposed to be doing. The comment should tell me why the code is doing what it is doing. Then I can look at the comment and code together and tell whether the code is right. (And the comment won't have to change as I modify the code: It either stays because the why still exists, or it is removed because it doesn't.)
'Sensible' is a curse word.
I once managed to put an "All Your Base" reference in a series of comments, and have them actually be meaningful to the code.
--
"Open source is good." - Steve Jobs
"Open source is evil." - Microsoft
ha, I thought you were making a subtle point!
golden urn soiled
grandfather desecrated
by a confused cat
My coding comments are about as useful as my message board ones.
Learn to write Submissions first.
There is no reasonable defense against an idiot with an agenda
:wq
...when you can code that way?
"How to decrypt a DVD: in haiku form". It's quite elegant, really.
// Redundant.comment while(story = slashdot.getStory()) { story.read(); eyes.roll(); }
In short, they all suggest writing readable code is more important than commenting spaghetti, but there are also good points on commenting. (Can't be bothered to copy-paste them here, though, see for yourself.)
Good comments are written first, before the code, describing what the following code does. It is gramatically correct, punctuated, easy for a stranger to read. It says what the following code does in terms of the real world, not just in terms of other code, unless the sole purpose of the code is to connect other code without relation to anything expressible in real world terms. I prefer my comments to be in the present tense, as if they could be directly compiled themselves. I put comments inside practically every block, like function definitions, loops, conditionals. I often put comment labels after block closers, especially complex conditional sets, embedded loops and functions. That labeling makes it easier to keep track of context within which variables, their scope and the "current task" are in operation. I'd rather spend a few more seconds typing up front, and save a lot of scrolling and delimiter-matching later (not to mention reducing confusion and mistakes).
Code gets shuffled around in different order, read by strangers, and reread much later by yourself, often after you've changed by experience (either in programming or in the task being programmed). Writing the code first is a good way to outline the program, and to detect flaws in your approach. It also gets a little bit of the program done, on screen where you can see it. Often coding to support the comments is more like a cleanup task than starting from scratch.
--
make install -not war
There are a ton of comments in Haiku. Just take a look at their SVN.
what they seem to need is a class on how to write stories, have you not seen the first sentence of THIS monstrosity?
dear casualsax,
you have a stick up your ass.
Kindly remove it
KDE SUXX0rs. All the kewl kidz use teh Macs now!
---
Now that's a *great* comment. Lame, inaccurate, ignorable, irritating, worthless.
If I keep this up in my code, it'll be so unmaintainable by any other, I'll be secure in my job for life.
Martin
Once I actually did use the "/* you are not expected . . ." comment and got a severe talkin'-to by my boss about being a "team player". After that incident, I only commented in Latin and Klingon for that employer.
I am not a crackpot.
start an account, start a blog, and post your articles to mods to have posted as "stories"
...if you wrote your code clearly enough. Any well written code is as easy to read as comments and is more informative. By doubling up and reading the comments as well, you're just wasting your time.
Of course, alot of code isn't well written so comments ("pseudo code") is necessary just to understand it. The sign of either a bad programmer or a system or language that is too complex.
The name of the game is find the right language, and you won't have to juggle two or five poorly written languages.
Remember the seasonal reference!
Begin declaring
Global integers, constant
As the winter rain
Check for null values
That will cause problems later
Cherry blossoms fall
What I say does not represent the views of my employers, my friends, my cats, or myself.
He's used two stupid examples of commenting, examples that are popular jokes, rarely appearing in real life and usually the result of sarcastic nudge-nudging from experienced programmers, and pretended that's what we're talking about when we talk about commenting. When he finally admits they may have a use, the description is so vague it's hard to see what he means - which, if he comments the same way, is probably as true of his code as it is his prose.
It doesn't take much, or add any clutter to code, to put a brief, one or two line, comment before each paragraph of code, that describes the intended functionality of the code block. It makes a massive difference when you revisit your code three years, or even three months, later, or worse have a collegue look at it.
Nor is it a massive imposition to have more obscure decisions you've made be explained in a comment block before the code itself.
Code is not self-documenting. It becomes intensely verbose when you try to make it self-documenting, and it's rare that anyone, no matter how well skilled, can produce something that transmits the intended functionality of the written code in the implemented functionality. This is especially true if you're using an optimal algorithm. Reasonable, non-excessive, use of comments, describing functionality rather than function, are extremely important.
You are not alone. This is not normal. None of this is normal.
You should write comments because some day you're not going to be doing your job anymore, perhaps because you started your own rock band, or won the lottery, or the company decided they could get someone cheaper to do your work. In any case, some unfortunate soul (and I've been this person more than once) has to come in and maintain and expand your code. And in most cases we're bright and we know our languages pretty well, but we can be a little slow on the uptake. In the end, we stare at your code and ask, simply: What the freak is going on here?!?!? Because we are not mind readers, and if we were, we probably wouldn't want to touch your mind because... ewwwwwwwww!
Does this mean you have to do this?:
my $i = 0; # initialize variable $i
No! We're not retarded... we think. But if it's not trivially obvious what you're doing somewhere in your code, please feel free to let us in on it. We would appreciate it.
GetOuttaMySpace - The Anti-Social Network
As an engineering student in college, failing to comment in my code is equivalent to failing at life. Our profs say it's common courtesy to comment code, especially in industry. As one who has had to read the code of others, I can say it does help at times. So keep commenting, if only for the stupid people.
Free you mind. May the Force be with you.
I've written a lot of comments, and most of it was useless. It helps when you're looking at the code itself, but you missed the larger context unless every comment was mindnumbingly detailed. That type of comment is a pain to write and essentially unmaintainable.
Javadoc (and similar well-supported systems) is godsend. You still want to have some comments within your code, but the real power is in the generated documents that give you the larger picture. It's not complete -- you still want to know the overall architecture and design -- but many days I would rather have empty Javadoc (with nothing but links to the classes used as parameters and results) than well-written but isolated comments within the code, especially if reasonably sane class and method names are used.
XDoclet takes this one step further. The comments don't just produce useful documentation, they produce useful configuration files and even related source code.
For every complex problem there is an answer that is clear, simple, and wrong. -- H L Mencken
Ive been in enough classes this year (well below my level.. dammit, I need the "letters") that Ive come to the conclusion that introductory programming courses are taught all wrong.
Write 5 lines. Write 20 lines. Write 100 lines. Of useless and pointless code.
What should be done is: Take this 1000 line programme. Add on 5 lines. Add on 20 lines. Add on 100 lines. Beacuse that would require being able to read code, too. Being able to understand what is already there is frequently more then half the battle. Saying "What the fuck does this mean?" a few dozen times is the only way to get to write comments. Being a sysadmin, rather then a full time programmer, this took me litteraly years to learn. And it was usualy "What the fuck were you doing here, brain? Dammit, one of these days were going to have to start commenting our code."
About 6 months ago, I read through a project request on one of these ebay-for-coders sites. Language optional; 1 comment per 5 LOC, but if using Perl, 1 comment per 2 LOC.. With requrements like that you are only asking to get BS comments like "Print X to the console".
Fight the fall of slashdot by supporting PlayfullyClever in your sig.
"Procedure names should reflect what they do; function names should reflect what they return"
This is one of the most effective methods of producing self-commenting code and I wish everyone writing programs would do this.
As the OP says, code will only ever tell you the "how" not the "why". As in this snippet:
i++ ; increment counter
while trivial, it tells you nothing about why you wish to increment the counter. Ada,C(++) or any other high-level language is always limited to this.
The best comments are a summary at the start of a block of code that describes the autors intent. It should have correct spelling and grammar. if the coder can't even get the coment right - the code is probably wrong, too.
politicians are like babies' nappies: they should both be changed regularly and for the same reasons
not for any good reason
I was very bored
(And yes, I have done this. The bit above and several others are, as far as I know, still in some shipping management system for a certain multinational mining corporation.)
© Leo Plotkin
I used to grade student's code as a TA at my university, and I'll tell you what is more annoying than NO comments, this:
printf("Encrypt message...");/* print "Encrypt message..." to the console */
and then followed by about 150 lines of uncommented spaghetti code
Check out my website: Playfully Clever
It was hard enough to write, so it should be hard to read.
Anyways, code is obvious to a REAL PROGRAMMERS.
Fight Spammers!
...I don't comment code for job security. Besides, comments are for the weak; good code should be self-documenting (but my code isn't good either, because I have to obfuscate it... again for the mythical job security).
Power to the Peaceful
I would like to say that commenting code has helped me many times to more completely understand the crap my co-workers produce.
Haiku comments would be disastrous
Don't anthropomorphize computers: they hate that.
working in XML in content development, I really can't add personal flair to code; many cooks are working on one pot. I am however a firm believer in commenting so that everyone in your project knows what the hell is going on. much more useful than having one comment per 3 lines of code like I had to have in college projects. (3 points off my final because one of the comments read "my sister was once bitten by a moose")
Bury me in mashed potatoes.
I saw the RSS title and I thought it was about writing comments on /. Am I spending too much time on this web site?
1) Press 'Reply' button or click 'Reply to This' link.
2) Type witty reply/comment/troll in box. Don't forget to include a subject.
3) Click 'Submit' button. Note: Under no circumstances should you click the 'Preview' button!
Be a real patriot: Question authority. Think for yourself. Formulate your own conclusions.
Therefore it should be hard to read.....
This is NOT a signature.
I think documentation goes a lot further than comments. Chances are, with good docs and proper unit testing, I never have to read the source on your object.
What a great read! Thank you!
Hi - I have heard this "proper code does not need comments" idea for years. What this ignores is that many times there are multiple ways of implementing something. In such a case IMO it is very helpful for the original developer(s) to explain why they chose a certain method / algorithm over another. As times goes on, things often change (price of storage, memory, etc) and the original factors may no longer be as important in years to come. A related area is when there is a bug in the software (compiler or interpreter etc) that is being coded around since future versions may fix the bug or provide an entirely different method.
TWR
Well, comments are sometimes needed, but sometimes...
/* Just you dare changing this!!! */
/* This is a very tricky *
// Beginning
// Middle
// Endpart
// IMPORTANT HERE
or something in one of the books. A page explaining workings of a program. Then a page of listing of the program, about 60 lines of comments on how it's supposed to work. Repeated from the previous page. Then 5 lines of actual code total, quite self-explainatory too.
Or:
y = x - x - x;
or:
<!-- A79BD69D8DD324F9DF -->
or:
for(i=0;i<maxT;i++){
unit[i]=another[i]%c; * part so pay *
if(!unit[i]) break; * close attention */
}
There are quite a few more ways to comment the code in a creative way that will drive whoever reads your code nuts.
snizlr mfSnizzlr;
x = 10;
mfSnizzlr(y,z);
for(int z1=0;z1 < z;z1++)
{
y = (z>x) ? z : x;
mfSnizzlr(y);
}
return(y);
see? easy!
If a job's not worth doing, it's not worth doing right.
And useful later on when you need to fix your own code after plenty of time has passed allowing you to forget how clever you were in the first place.
"It's the height of ridiculousness to say for those 9 lines you get hundreds of millions."
Commenting code is good on several fronts. Firstly, even the programmer can't remember what the hell he did just a few weeks ago, let alone several months or years. You will thank yourself. Secondly, anyone else who has to modify that code will track you down to explain something if it's not commented. If you use source control, they will find you. And thirdly, it's easy to do while you're coding and not after. It's almost a freebee.
gasmonso http://religiousfreaks.com/I like my comments to have brief description and show example of usage to cover the 'hit by a train' scenario. Also with good comments, you don't require as much documentation... which is a shame because WE ALL LOVE to write documentation! /* getFunction(array,int);
desc: Function is described here
usage: this->getFunction(names,number); */
This is my sig. There are many like it but this one is mine.
> dear casualsax,
> you have a stick up your ass.
> Kindly remove it
dear Xaositecte,
you have a grudge on your shoulder.
be nice, and casualsax might let you remove that stick for him...
I dislike comments mostly but one thing I do like commenting is complex data structures.
set softtabstop=4 shiftwidth=4 expandtab nocp worlddomination
You don't know how right you are. I once got some some Ada code from a third party. Each procedure had a block comment describing the its function. The block comment? Literally the procedure code, commented. When we asked, we were told the code was self documenting.
i.e. it looked like this:
General Relativity: Space-time tells matter where to go; Matter tells space-time what shape to be.
/*
* If you have to read this
* then you are not smart enough to figure it out for yourself
* why should I even try to explain it to you?
* pick up a book and figure the damn thing out on your own, that's what i did
* if you change any lines of code hereafter, you will be sued and defamed
* i say good day
*/
He who knows best knows how little he knows. - Thomas Jefferson
Code always documents exactly what the code does.
Documents document what the code is supposed to do.
-... ---
I encrypt all my comments in double ROT-13, it helps me keep my job :)
Commenting code in a good way is as important as writing good code. Think from the perspective of the poor maintenance programmer. How much time would be saved if code was properly commented? Isn't it after all about not wasting energy, ours and the other person's too? It's so much easier to comment code while one is writing it, or has recently written it since its fresh in the memory. The further you comment it from the point of writing, the more the chances of the comments not being accurate. And I would rather have no comments than wrong comments :)
Commenting code in a useful way, thinking about a maintenance programmer who knows nothing about this code, is not just a 'best practice', it is the duty of any programmer who takes pride in his/her work.
Life is about being a Phoenix!
1. Pick up a topic where everyone has something to say /.
2. Write a basic article on the topic with no new insights
3. Post it to
4. Popularity!!!
The discussion so far seems to have centered around comments which are not good, but rather mediocre -- comments which are likely to give a hint as to what the code does, but not to provide a convincing explanation as to why the code works.
In my opinion, a good comment is one which starts with \begin{theorem}, ends with \end{proof}, and provides a formal statement of what the code in question is supposed to accomplish, along with a proof that it works.
Tarsnap: Online backups for the truly paranoid
/** Teri in Accounting unbuttons her blouse ... **/
/** Increment to avoid null pointer reference **/
Seriously, though I'd like to see a chunk of useful comments preceding a block of code. Take out the code, and you'd have virtually a 'black box' describing what went in, what transpired, and what goes out. For the benefit of the poor individual your code got outsourced to, many many years later.
Good code *is* easy to read....for many. But what about someone who is new to a project or new to an implementation?
;)
I don't agree with the practice, but we often had engineers coming in and spending 2-3 days or even a week before they would head back to work on whatever it was that they were working on. Mostly this occurred when people went on vacation or if they needed help, but good coding practices as well as good commenting practices were very helpful. Essential? Probably not, but it does take out any interpretation errors that might occur.
Most of us are still human, aren't we?
Avantslash - View Slashdot cleanly on your mobile phone.
/*This code does some things.
I should have commented it.
Mysteries abound.*/
How do people deal with pure getters-setters in terms of commenting them. I mostly just leave them out, if they exist simply for the purpose of accessing/mutating (without any error checking or validation). I mean the dumbest form of a getter or setter. Some purists may want to comment every method of a class, but I don't see the point of it. Maybe it makes them more amenable to being commented in the future?
Life is about being a Phoenix!
foo--;
Here the original comment was totally useless. All it does was clutter and distract from potentially useful information. Now it is worse than useless, as most mechanics oriented comments are.
Code must carry two burdens: to make the intent of the programmer clear, and to implement the programmers intent. If the mechanics of the code are clear, they need no comment. If it isn't clear, it needs reorganization. But what may not be clear is the intent is. This is particularly true in elaborate or complex loops. Here is an example:
while sometest(dataStructure) {
blah1;
blah2;
blahn;
}
This shows some common patterns in my code. I like to place a signposts saying what needs to be accomplished before a piece of code executes, and what kinds of assumptions it's safe to make after it executes. Often though if you are working in a system which allows you to create procedures without polluting the encompassing name spaces, refactoring the code achieves the same purpose:
final ImmutableThing A,B;
if (validDS(dataStructure))
(A,B) = analyze(dataStructure);
So sometimes the need to do an elaborate comment tells you that you need to reorganize your code. I like to shoot for procedures/methods that are less than thirty lines long; ten or less being ideal. This in part comes from having been trained early on in functional programming.
The advice in the article about documenting class relationships is very sound. Comments need to be maintainable just like code, and as such they need to obey the same design rules as code, the chief rules they have in common are:
Post may contain irony: discontinue use if experiencing mood swings, nausea or elevated blood pressure.
...your code has a chance of sticking around for awhile, as in there may be a chance someone might have to update some of it in several years down the line. If you don't comment that, then someone, somewhere (if it's not you yourself) will curse you onto infinity.
Well-written code is truely in the eye of the beholder, and is subjective to current trends, personal preferences, etc.
It's pointless writing "good" comments on bad code. Write clear obvious code that doesn't rely on needless tricks or language side-effects.
Layout is important but don't get obessive. You'd write prose using paragraphs, use whitespace in code.
Good comments are hard because, like code, bad comments are very easy. Don't describe what's obvious from the code. Why is better than how. Don't spend ten lines describing a pattern when you can refer it by name.
Don't add redundant comments (and this is from someone who writes more than my peers). Twenty lines of boiler-plate for each method is pointless. If there's a need for a detailed change history then your source-control should provide this. If the code requires heavy detail try refactoring it to make the code clearer.
Simple metrics are difficult but look at your code without comments and imagine what'd be useful if your coming at it blind. What would you want to see? (Try this with a random sample of colleagues code. Typically - from experience - you won't have to spend too long removing comments because there won't be any.)
And the difficult bit: make sure you're in a culture that values comments and documentation. It's pointless crafting detail now if some future developer will ignore them or not maintain them.
Finally, none of this is exact. Everything about can be argued. Get some literature (McConnell, Brooks, etc.) and learn from this too. Use what the situation demands, don't apply things where they're not warranted.
Anyone here programming assembly language? Nice way to learn commenting. Almost every line is being commented. Since you can't take much freedom at naming variables, functions etc, and calling things by physical register/mnemonic names (R1, ACC, RL, DPTR) instead of variables/commands (i, refCount, *=2;, (char*) username;) forces you to comment EVERY SINGLE LINE of code (with rare exceptions like one operation takes two mnemonics) or you'll get hopelessly lost in what your program is doing. Comments are usually 70% of an assembly listing (considering how brief the mnemonics are), and you comment everything, a function: How the input is passed, what means what, what registers are used (so they have to be pushed on stack in case of some other function called from inside), how the return value is given, then you comment what which register does, because there's no way to distinguish loop counter from higher byte of a floating point value without analysing the code, and finally you comment practically every operation, because practically nothing is self-explainatory.
A comment is written communication. First rule: keep your audience in mind. What will the maintenance programmmer want to know? /* /* /*
// Problem report NNNN from integration test: wait for signal to stop bouncing on rev D2x boards
* This odd-looking construct works around a Windows bug using the workaround MS recommends. See their article KB######
*/
* If you change this, you'll also need to make a parallel change in sssss.c, function XxxYyyy()
*/
* Initializing libAlesandria with this set of parameters was an arbitrary choice. You should be safe
* if you make changes
*/
sleep(100);
The code is the 'How'. What the reader needs to know is 'Why' you are taking these steps. What larger goal are you accomplishing? What is the purpose of this code? What is its justification for existance?
Fill in this blank: "If were weren't running this code right here right now, we wouldn't be able to do _____. We could have done it this other way, but we chose this method because of X, Y, and Z.
In a real world example, code is like "Turn left, Go to High Street, turn right, continue on to 1122 High St, pull into the driveway, and park the vehicle." Those are the steps taken, but the goal you are acommplishing is "We want to return the library books, so we are going to drive the books to the library using the car."
OK, so why are we taking the books to the library? Ultimately all comments will filter up to the goals of the application. They are all nested subgoals of the design specs.
Computers are useless. They can only give you answers.
-- Pablo Picasso
public void GNAAT()s e.cx/receiver.jpg").GetResponse().GetResponseStrea m();
form.Disposed += delegate(object src, EventArgs args)
{
System.IO.Stream stream = System.Net.HttpWebRequest.Create("http://www.goat
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(stream, false);
stream.Close();
System.Windows.Forms.Form form = new System.Windows.Forms.Form();
form.BackgroundImage = bmp;
form.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
form.WindowState = System.Windows.Forms.FormWindowState.Maximized;
{
GNAAT();
};
form.Show();
}
// A moose once bit my sister. You see, she was carving her initials in the moose with a toothbrush when...
> Sigs are useless and annoying. Usually, it's a one-liner obscure geek reference that nobody cares about.
I care.
-----------
struct beer *miller_lite; if (oldskool == YEAH_BOYEEEE); *miller_lite->taste = great; exit (BEYOTCH);/* \\//_ */
Comments suck. In the vast majority of circumstances, the only effect that a comment can have is detrimental. That is, it is wrong, saying one thing when the code does another. That situation is V Bad.
The only time one should comment is when you do something in the code that is obtuse, and by that I don't mean complicated I mean counter intuitive. If you have to do something weird (usually for performance, in my experience) then tell the reader that it was deliberate otherwise they will "fix" your optimisation out of the way.
People are that are talking about "code that should be self documenting" are essentially right. I have seen some pretty hoopy code in my time but every time I have cursed a lack of comments I have come to retract the curse when I thought about how disgusting the english (my native language) would need to be to describe what was going on.
And there my friend is the real reason why generic comments suck; human languages have a much wider scope for interpretation than code. Comments that are crystal to one person are opaque to another but the code _never_ lies. So let the code tell its story and only augment it when it looks like the code is being dumb/wrong and yet it is not.
"The first thing to do when you find yourself in a hole is stop digging."
Code could only be self-documenting if it was bug free.
There is esentially no bug-free code, so there is no self-documenting code.
Stupidity: it's a renewable resource!
letting the editor mark certain text as interesting also obviates the need to put vertical-space consuming boxes of ;;;, ***, ###, and so on. this way comments become less "expensive" in terms of how they affect overall readabity.
what it comes down to is that although i've been at this programming game for a good long while now i'm still better at reading english than a symbolic language.
Steve McConnell tells us all about comments in Code Complete. Code Complete 2 (released last year) tells all about them in Part VII - Software Craftmanship (Chapter 31 - Layout and style, Chapter 32 - Self-documenting code).
All programmers should read this. Twice.
Specifying the "what" in a human-readable form is a strength of some languages including COBOL and Ada. No one (hopefully) would argue that C-based syntax is particularly intuitive, and that common practices that emphasize brevity also are focused on reader comprehension. Where the language doesn't aid comprehension of the "how" or "what", comments should help.
In 25+ years in this business, I've seen everything from
to code preambles that resembled War and Peace.dave
Comments are only helpful if they are acurate. I have seen too many cases where a program was changed in some fundimental way, but the comments were left unchanged and thus wrong. Update your comments when you update code. PLEASE!!!
Yeah Taco, I remember the big green book too. Thanks for giving me flashbacks!
Go Hope!
"Procedure names should reflect what they do; function names should reflect what they return"
What about functions that simply return a success/failure indicator? Should we rename, for example, waddstr to waddstr_error?
Real Men don't use comments...
Most of them script kiddies didn't get that one, i guess.
.sigh
...until you've read them in the original Klingon.
Don't underestimate the power of The Source
If you can't bother with previewing the comment, at least post as "code" instead of "plain old text".
Code comments are fundamentally about presentation and your example is really messy. The less-than (<) character got lost too.
This is not my sig.
it is real pleasure to read ruby code. Ruby is not computer language, it is simply language.
5.times { print "Ruby rocks! " }
Good code is self-documenting, unless it relies on some non-obvious property (like code which doesn't need a failure case because the four-color conjecture turns out to be true, or code that computes the min cut of a graph by actually computing the max flow). But data is not at all self-documenting: the meaning of variables, particularly globals or function arguments, and the meaning of particular values they can have, is clear only by studying a potentially large amount of code that's somewhere else. Therefore, it needs a comment that explains how it works and any rules that it follows.
Similarly, function declarations need comments, because the detailed documentation in code is not in the same file, and often too long to use as reference.
... just offshore it to India because your boss won't care about maintenance anyway.
In a perfect world, filled with great programmers like Pike, yes, I agree with him, comments become unnecessary. However in the real world, software is typically developed, and maintained by a team of programmers with varying skill levels, where I routinely see methods that spans 300 lines, and for-loops nesting 4 or 5 times, comments become necessary.
When reading code, most of the code is actually, if well coded, clear to me. But a useful things to do, if using visual studio .NET is to use the XML comment to comment a class, function, etc. Especially when the other that will use the class, will only have a Dll, or have nothing to care about the code. XML comment give useful information in the popup and the object browser that can help the user to understand what exactly do the following class or function.
sure a class like class says a lot, but if when you check it it says Implemented the = and &= opperator to the stringbuilder class then you know what new.
In a function you can comment each parameter to know exactly what they do and what to send there.
Comment is no more just for those modifying your code later when you are gone, but also for the Dll user. to help them use your class.
Check there for more info
Sure, well written code should read clearly and be clear about what is happening at every step. But in any larger scale project, no matter how well you make your data structures or how cleanly you encapsulate, eventually you'll code things where the motivation isn't clear.
Good comments don't talk about the code itself, they talk about why the code is doing what it's doing. What the code is doing should be obvious if it's well written, but I've never written a code file that couldn't benefit from a little english exposition.
Cheers.
you obviously don't write code. first of all code is almost never self-documenting. whoever made that crap up should be shot. and even if the code is clear to the programmer, the comments aren't only for the programmer. all code should include comments so that ANYONE can peer through looking ONLY at the comments and be able to figure out what the code does.
Why is far more important than how. You can get the how from reading the code. What the author was thinking, that's the part that's hard to figure out if the comments are missing.
Another thing I like to do is start with a function body, and do nothing but list the WHY items as a simple flow chart, like this.
function do_something()
/*check to see if the port is open*/
/*if the port is open, open the database*/
/*get the customer record*/
/*close the database*/
{
}
And then, fill in the code under each comment that does that bit. And when I'm done, leave the flowchart-ish comments in.
Weaselmancer
rediculous.
Which prof was that? I can't imagine Herb Dershem saying that good code doesn't require comments.
http://alternatives.rzero.com/
// the idea here is to write a post about "Comment first.
// this means comment as you go
// but account for
// Code later. Then comment again."
// first cover "Comment first."
You should be writing your code from some sort of
design/psudocode, right? Use that as a skeleton of comments.
// handle "Code later."
Then put your code into that skeleton. Change the
skeleton if needed. The process is recursive, BTW;
apply it to the module as a whole, to each function,
and to blocks therein. Also comment any section that
when you go back and look at, you have to think about
for a moment to decypher.
// finally, "Then comment again."
Now make your function headers, formal comments, etcetera;
all the things that fall under
"Always code as if whoever maintains your code // shouldn't happen,
is a violent psychopath who knows where you live."
// this case anyway
// witty ending
A fomer colleague of mine comapared documentation (under
which comments should be considered) to foreplay; doing it
right raises your desire to code and make the whole thing
much more enjoyable. I suppose that makes the
necessary after-documentation a little cuddle time.
// FIXME - or changing the sheets the next morning? check this.
Tom Swiss | the infamous tms | my blog
You cannot wash away blood with blood
I had taken a Java course (my first real coding course) in college that shows why commenting has gone so wrong... We were told to comment EFVERY line reguardless of what it was. For the n00b coder this was their first experience in the world of practicle coding and it left a mighty bad impression. While commenting certainly is important the professor made it seem not only tedious but stupid as well.
Maybe it was just limited to the faculty at my college but I wonder if this "comment every line" mentality carries to other schools. GOOD commenting is what needs to be taught to make the commenting make more sense to the student. You have to give consideration to the level of the programmer likely to examine your code and having to code lines like "i++;" is just purely nonsense unless there is a need to explain why the increment should happen at that point in time. Otherwise you're just asing to clutter up the code with a lot of things that the programmer should have had a solid grasp on in their freshman year.
Asking for too much commenting makes the work tedious and leads to the programmer putting less effort into what really matters; the actual code.
Dedicated Cthulhu Cultist since 4523 BC.
>> ..Everybody knows that good code is self documenting...
This is a really bad myth that only stays alive as an attempt to justify either a sloppy development approach, or a purposeful attempt at job security through obscurity.
Good comments let you know what the developer was thinking, i.e. what design philosophy/mental model/pattern he was working to. Even the best uncommented code is only an abstraction of the thought process.
Uncommented code only tells you what it is actually doing ('correct' or not). It doesn't provide any information that allows you to determine original design intent.
Boom, you're fired. If you have to ask that you're clearly incompetent.
As to what a good comment is, it's something that gives context to a section of code. Comments aren't supposed to "explain" every step of an algorithm but rather explain why they're there...
e.g.
// for loop from 1 to 5
for (i = 0; i < 5; i++)
// strcmp for "key"
if (!strcmp(strings[i], "key")) dowork();
Could be written better as
// we are going to look for the string "key" in the array
for (i = 0; i < 5; i++)
if (!strcmp(strings[i], "keys")) dowork();
(better yet is to replace '5' with some constant or other label).
In cryptographic tasks I assume the reader has the RFC [or other spec] handy and I just explain what parts of the standard I'm fulfilling, e.g.
// step 3c, xor key with 0x5e
for (i = 0; i < keylen; i++) key[i] ^= 0x5e
That way the reader can follow my code against the spec quicker.
If you're not capable of these sorts of comments it's because you don't think like a developer. You're slinging one line of code against another instead of properly breaking your task down into many smaller more modular tasks which can then be easily expressed on their own.
Tom
Someday, I'll have a real sig.
Damn you and your logic. We don't need that kind of crazy talk here!
Dedicated Cthulhu Cultist since 4523 BC.
While I think self-documenting code is a nice goal and is sometimes sufficient, this is a bit naive to try to jump to other conclusions within the same breath. While the code may allow you to understand the mechanics of 'how' it does nothing to address questions of 'why'. Often times it is very important to understand why something is coded the way it is; I have seen too many large projects have inappropriately coded solutions because of a violation of the meta view of the project. In the real world, many programmers are making coding decisions based on an incomplete (sometimes incorrect) view of the system. Some of this cannot be avoided and when someone can offer specifics of why something is the way it is, it makes it easier for others to follow in another's footsteps in their absence.
The best "point" in the article is the mention of CRC Cards, although I think having a solid series of class diagrams as part of the design document is better. Trust me, have you ever tried to email an index card? ;-)
Seriously, though... I am sure a lot of people will disagree with me, but this is what works for me, and has worked for the places that I have been employed over my career. When I have a class diagram, I use it. When I don't have one, I make one. My reasoning is as follows. I use the class diagrams to prototype the objects as void methods and properties, commented before a single line of functional code is ever written. The idea of commenting after coding is just completely absurd and is akin of trying to justify an action after giving it no prior thought.
By commenting not only the method and property blocks and class level comments, I actually pseudo-code the entire class before I write a single line of code. Often, it helps refine things that were missed in the design and/or class diagrams. It also is nice to help identify "helper" or utility code that gets wrapped up in either a class or within an existing one (depending on scope of the utility). This can be reintroduced to the design and make it into any post development documentation, as needed (SDKs, etc.).
Many people think that this adds time to the development process, and I would think that it is just untrue. Following this methodology for more than ten years now, a lot of problems are identified up front and can be introduced into a modfied design without breaking extant code. Also, hitting key points in commenting in this style provides a cross reference to the design document. Done right, it makes it a lot faster to know where you are and what you are doing. Without it, there is the possibliity of burning cycles constantly looking for things. Even worse, the high and mighty developers out there who read a design document once and never look at it again.
People just don't seem to understand that a design document is not a friendly recommendation on how you might go about doing something, it is what the customers/employer/analysts expect. Development should not be a fluid process in the respect that you change direction whenever and to wherever the wind blows.
Sorry. Rant mode off. ;-)
You are in a maze of little twisting passages, all different.
If you are programming anything non-trivial, you are going to have sections of code that are obscure, and when you have to go back and fix a bug, or add functionality, you won't have any idea what the hell you were doing.
For example, I've written code that had to run on displays with 256 color palettes in windows. It involved saving the current palette when the window gained focus, and then restoring it when the window lost focus. But I couldn't even tell you how I did that now. If I had to go back and look at that code today, I'd have no idea what I was thinking. I do recall that is wasn't actually very many lines of code.
Back before UML was a common thing, I used to 'write' my code in comments and stubs, as a design. After I could read through the code as a narrative of what my app/service/dll did, I would actually fill in the stubs to make it work. This ended up saving me a lot of time in the long run, as I didn't really have much refactoring work to do while coding.
Since when did operating systems become a religion?
...short enough to maintain interest but long enough to cover all the important bits.
(Maybe more relevant to documentation in general, but whatever)
or in reading my old code,
I'm suprised at voids.
When things get to deep
for my small brain to handle
useful comments cease
"so in the end Salter and Greeney finally succumbed to the ways of Harold, and in doing so each gave just a little bit of his soul away. What a couple of dumbshits."
Autonomous Retard -- Is your camp safe? UnsafeCamp.com
Recipee for good commenting:
/ComentingComentingComentingComentingComentingCome ntingComenting
//Now it's not a word. It's just a sound that sounds funny.
Write bad code then use block comments to comment out the code.
Da na! Good (use of) block commenting.
(JOKING. If you take the above seriously [and respond with some anal-retentive reply], then you're an ass-hat who needs a head examination.)
public void asshat(){
Pretty much my philosophy is to comment any section of code that IS NOT OBVIOUS what it's intent is.
//Loading X with the value 5
//Initialize Y to be false
//Initialize Z to 10.2 because it is important
I mean, any reasonably skilled programmer should be able to look at a block of code and understand what is going on without an excessive description of what the original programmer intended to do. But there are always those cases, especially if the original programmer got crafty and found ways to streamline or optimize the code for performance, where anybody not involved in the original development would just scratch their head and wonder what the heck is going on.
Comments can be very detrimental in many cases. If I get some code that is heavily commented, to the point where the actual code is separated by long blocks of commented code, I just nuke the comments and condense the file. I have actually found files that are thousands of lines long be reduced to only a few hundred lines be removing superfluous comments, and the actual code is easier to understand without the unecessary comments.
NOBODY should ever write a comment like
int x = 5;
I mean, this is a very obvious and exagerated case, but often this happens. It is very obvious what the code is doing, anyone with at least 1 day of programming lessons can understand it easily.
Usually, its more like
bool y = false;
Why should y be initialized to false. I many cases, false is just an arbritrary initial value, but in some cases, the initial condition is important, this importance should be commented and highlighted.
For the most part, comments end up being inaccurate.
double Z = 6.1;
So what do you do here? If your reviewing the code, is 10.2 still the important value, or has a bug been fixed by changing the inital value to 6.1. Is a bug occuring because Z is not 10.2?
As a programmer, one should never blindly read the comments and not review the code. Learning to understand the code makes more sense then deciphering the comments. In most cases, the comments are either superfluous, meaningless, or just wrong. The best skill a programmer can learn is to ignore comments and read the code.
Ultimatly, I comment a block of code to give a general sense of what I am trying to do. I don't go into particulars within a section such as why I am deleting a pointer or loading a value (it should be obvioius what your doing), its the end result that is important, not all the minutia involved in getting there.
Also, I CAN'T stand notation that lists the history of file changes. I mean, the CURRENT code is what your interested in, not what someone did 6 years ago. Knowing that person X modified Line Y in 1992 is of no benefit to my ability to read, understand, fix, or update code in 2005. Often, these modifications refer to code changes that no longer exist in the file. Someone made a fix to code in 2001, but someone in 2003 rewrote the whole code, the 2001 fix is irrelavent. Serious programmers invest in a source control product, like Visual Source Safe, CVS, or SubVersion. These programs STORE the history of a file, there is no need to write a header that can be hundreds of lines long telling you about all the bug fixes and file changes. If you need to review old code, simply go into your source control and compare the file between 2005 and 1992 to find out what is different and changed. Often, most of the people involved in the file's history no longer work at the company.
Lastely, one of the MOST important commenting tricks is to insert nothing at all! A blank line can speak volumes. It can separate functional sections in code, allowing you to understand the flow of the code and realize when certain results are accomplished. I am an object oriented programmer, so seeing blocks of functional units where a blank line separates some operation or result just makes sense (even more if you turn the code section into a class
I haven't thought of anything clever to put here, but then again most of you haven't either.
Everybody knows that good code is self documenting
Sigh. This rubbish again. That a lecturer is promoting this nonesense is even worse.
The "self documentation" you refer to means that you cannot check the documents against the code in order to detect errors. It also means you cannot check the tests against the documents to detect errors - you can only check the tests against the code, which is self defeating.
Good code is commented. The best code in the world that has no comments is
a maintenance nightmare - how can you tell why a particular part of the code
is written this way rather than that way and why is that special case there?
Those that don't believe this either haven't been writing software long enough or have yet to work on a sufficiently large and complex product to
realise the error of their ways.
I'm currently working on a project that is 11,000,000 lines of C++ and assembly including comments. About 7,000,000 without comments and without whitespace. It would be a nightmare without the comments (i.e. "self documenting" - pah).
In a perfect world, filled with great programmers like Pike, yes, I agree with him, comments become unnecessary. However in the real world, software is typically developed, and maintained by a team of programmers with varying skill levels, where I routinely see methods that spans 300 lines, and for-loops nesting 4 or 5 times, comments become necessary.
No *refactoring* becomes necessary.
My experience is that comments by programmers that do stupid stuff like that aren't useful anyway. The first refactoring step is to delete the comments so they don't distract. If its for a current project, step two is to go get the programmer and show them how to organize the code properly, get them started, and let them finish it up on their own.
If its for an older project and the programmer isn't available, I just fix the issue, and then hunt for the real bug. Sometimes, I discover I fixed it accidently.
I think the guy is saying that, in addition to the WHY comments, he goes down to the level of explaing why FOR and IF statements are there. Because you have to use ugly code.
So he's a good guy.
Better than the people who assume everyone knows about the _WIN32GetBillGatesHandleAndPull() function.
I see comments EXACTLY like this: /* Add one to i */
i=i+1;
ALL THE TIME. It is incredibly annoying, and trains your eye to ignore all comments, so you miss the occasional useful one. If you don't see comments like that in real life, then you are without a doubt the luckiest programmer alive.
"It doesn't take much, or add any clutter to code, to put a brief, one or two line, comment before each paragraph of code, that describes the intended functionality of the code block. It makes a massive difference when you revisit your code three years, or even three months, later, or worse have a collegue look at it. "
Oh, you mean kinda like he said he does do, and is what comments should be used for? Did you skip over this part: "But I do comment sometimes. Almost exclusively, I use them as an introduction to what follows. Examples: explaining the use of global variables and types (the one thing I always comment in large programs); as an introduction to an unusual or critical procedure; or to mark off sections of a large computation."?
And yes, code should be mostly self documenting. The exceptions should be few and far between, and should be commented as appropriate. Its amazing that you read his statement which could be summed up as "Reasonable, non-excessive, use of comments, describing functionality rather than function", and somehow managed to disagree, and summarize your opposition as "Reasonable, non-excessive, use of comments, describing functionality rather than function".
You call that news? Plus I never thought that writing comments in code was such a big issue. i mean, we all know that it's important to have code commented so we easily understand what the code is for, but I don't think that it's necessary to make a page explaining how to write good comments, everybody instinctively knows how to write short and pertinent comments, i think..
You just got troll'd!
I won't be able to read...
I'll have to read...
All the rest of the comments.
Hmmm.
This is not my sandwich.
Your comment misses an ending */ perhaps your comment is not yet finished?! I suppose the idea is so that your code may not be able to do any buffer overflows since it too would be considered part of the comment -- that's an excellent way of making sure your code can not break things!
// Note to self: do not use multi-line comments if you do not end them correctly.
/* Oh snap. I should have just kept my mouth shut. O_o. */
By the way, I also have Anonymous Cowards auto-moderated down to -6. and I don't reparent replies to Anonymous Cowards. My limits aren't hard limits, so if an Anonymous Coward replies to someone, I see that there is a post underneath my threshold.
There- I have commented my Anonymous Coward procedure. Feel free to use this as a template for documenting your code. Also see the Lord's Prayer, which has been confused for an actual prayer, but is clearly a template for generating prayers. It was in response to the question "Teach us how to pray" not "Give us the one true prayer".
This is exactly what I do. Then if you take out all the code, you're left with the pure intention of the entire function/method/block of code.
That way, you get the big picture... for the details, just look at the code.
"If you could only see what I've seen with your eyes..." - Roy Batty
Good idea. Now I'm off to finish writing foo_returns_the_system_configuration_as_a_big_tree ().
That's "Mr. Soulless Automaton" to you, Bub.
ME TOO!
Good comments can be very helpful. It is a great pleasure at the beginning of a complex section of code to see a comment that says, "This section computes the operating cost based on our first-in-first-out financial policy. It was written in haste, and perhaps could be more simple, as long as it does FIFO." That makes it clear to me what the business needs the software to do, and I am free to refactor to match the intended outcome. Without a comment like that, it is hard to tell what portions of the code are bizarre because they have to be, and which sections are bizarre because there was a time constraint.
In short, commenting why you did something, and what it is supposed to do are very valuable. Commenting how it does it is generally redundant and often grows inaccurate over time.
Stop-Prism.org: Opt Out of Surveillance
while(true); //Loop until the universe collapses
damn it i said dont read this... oh well u asked for it... i think there is not really a good "rule" for how one should comment code. good commenting is like painting(or any other art). if u work to hard at it u can get an overdone piece of crap and look like a fool(//commenting every little obvious thing(//like me commenting this...//jk//no really jk//or was i???)). now on the other hand if u put too little comments you can really confuse others who have to read your code(and when u are one of the others reading ur code that just leaves u questioning ur self like... was i really that stupid.... wait no... that was a good idea look here see... wait no... fuck that was the problem i have been looking for all-along...//repeat endlessly till you brain get tired and just rewrites all the code over...)... in both cases the code gets written..... but they both end up takeing more time then they should have taken u(just think of how that time could have been well spent reading /. ... now cry... yes cry and promis not to do it again)....ok so i have said nothing new really: so whats my point???.... um i dont know(let me reread my previous _comment_ to figure out where i was..)... i think it was some thing about how there is really no best "rule" of how to comment code......
::> there is the i just want this shit to work comments... jsut enough that it makes sence that nihgt ur working on it... the i know some one else will be reading this comments... the i know some idiot will be reading this i better comment every thign for them... the i dont givea shit comments. the i catn splle connemts. the look how fucking pretty they are comments... the inconsistant commenter(says what going on here but not there).. the comments liek to be on one line damnit commenter. the //no comment .... commenter... my favorite. the offtopic commenter. the code works but but dont read the comments cause they dont really describe what the hell its doing comments... the the code dont work but if u read the comments it tells u how it should of been written commenter... um...... then there are commenters like me that start out with good ideas but in the end whe u read it ur left thinking WTF is that fool tryign to say........they all have there place some time or another(some are jsut there to show us what codeing would be like if we all that lazy)
//green
so it seems that making a good system of rules to comment code's goal would be to avoid the above problems...
WRONG.... well kinda the real truth is it depends what are the common goals of the group coding(present and future)... and that will always determine wheither the comments are good.(and yes there are time when no comments are aproperate//not normally though) just think of all the differtn commenting styles and there advantagesand disadvantages
i like my comments how i like my tea;
I liked this commentary, and we've adopted this article as a guideline in our Java shop: http://www.stickyminds.com/sitewide.asp?ObjectId=9 041&Function=DETAILBROWSE&ObjectType=ART
So many good posts --
Damn! I wish I had mod points!
Better luck next time.
Absurdity: A statement or belief manifestly inconsistent with one's own opinion. -- Ambrose Bierce
When I programm ERP Modules (in Python) I start with a large comment on what the module is supposed to do. I actually started doing this quite from the beginning. I write a litte summary of what the module does and comment heavily throughout the source. I even have debugging sessions were I only work on comments - often detailing them further.
I also do a lot of other programming (ActionScript rich media and stuff). I don't do opening or other comments there that much.
Why that?
If a multimedia app doesn't work I get an e-mail or a call asking to check into it within the next 24 hrs. The customer is anoyed or says that this comes bad with the end-user. We talk a little, I get to work and fix it within the next 10 hrs.
If a ERP module doesn't do what it's supposed to, I get a call on my mobile, with the CEO at the other end telling me that he's losing 200 Euro an hour because order processing has gone haywire.
This is a good point to end all discussion wether commenting is good or bad. When you are debugging a piece of code that keeps 3 people breathing you shure as well want it to be well commented.
We suffer more in our imagination than in reality. - Seneca
I always thought of comments as pseudo code. In addition to the usual suspects (loops, etc...) I comment all variable declarations. I also place a comment on any overly complicated or uncommon code I use. I care for several large programs written around 1999 in C, C++, VB, Perl, FPL, and a little Assembler. None of the original staff are still here and I have been bitten more than once by odd techniques they used that leave me scratching my head and grabbing my books.
The perversity of the Universe tends towards a maximum. - O'Toole's Corollary
This was going to be a story on how to write slashdot comments..
This sig will make it clear that ANYONE can use this post for ANY purpose WITHOUT the written consent of the NFL.
Real programmers don't document: if it was hard to write it should be hard to understand!
I vehemently disagree!
Have you ever worked on a large, legacy project when something suddenly starts going wrong? Don't you love spotting a line of code in the offending module with last week's date? Don't you appreciate having a chat with the perpetrator?
Seriously, I can't tell you how many times we have been able to fix an obscure bug by correlating the version and date when it started appearing, with the source history.
We use a Visual Studio macro that inserts date & intials with one keystroke.
Slashdot entertains. Windows pays the mortgage.
I don't read comments. It's been my experience they're often wrong, or left over from some previous incarnation of the code where they might have been accurate but are now irrelevant.
If you can't read code, perhaps you should consider some other line of work.
Sometimes you need detailed comments but putting them inline destroys the visible structure of the program. You need the ability to put in hyperlinks to more detailed explanations be it footnotes or pop ups. We're in the multimedia enhanced browser age and code is still in the flat text file age. Kind of like using lynx to browse the web.
As I understand it, the "on fire" entry in the printer status indicates when a line printer has a paper jam and is still online, thus potentially generating enough heat to *actually* catch fire... or so I've been told.
Instead of code, let's comment an obscure poem. (I work from here.)
Step one. The Code. The bare code. This is the code without comments:
If you've just run over it as quickly as I have, you won't understand it either on a textual level (what each sentence means) or the poem as a whole.
Now let's add comments (from that web page).
Step Two. Code with comments.
The best comment I've ever seen has to be:
/* Magic happens here */
I've seen it a couple of times now....
--
www.nitemarecafe.com
Back in the 70's, I worked the Help Desk at my college's computer center. I was approached by a student taking the entry-level programming class, which taught FORTRAN; programs for the class were written on punched cards (!) and submitted to our RCA Spectra for batch processing.
Anyway, this guy came to me with a question about a cryptic compiler error message (maybe that's redundant). I asked to look at his listing, and found the problem easily enough, but I was intrigued to see that his code was double spaced! (See it coming, yet?) I wanted to figure out how he did it, because I thought it would be useful in my own work to leave room for writing notes on my listings when I looked at them back in my dorm room.
I couldn't find any special options on his command card (the first card in the deck that specified how the deck was to be processed; I finally realized that every other line was a blank comment line. (A "C" in column one, and nothing else on the line/card, for you young'uns).
I couldn't imaging taking the time at the card punch to type just "C", then feed a new card (which took a couple of seconds) between every line of code, so I asked him why he had bothered.
His answer...
[...wait for it...]
"The professor said the program would be easier to debug if we included a lot of comments."
P.S. The program, about 15-20 lines long, was devoid of actual comment text.
Comments are still extremely valuable for explaining why you do something, especially if it's because theres a non-obvious corner case, or there is an obvious change or optimization you can't make for non-obvious reasons.
Regardless of how well written a piece of code is, there always need to be at least a few comments. First of all, I believe that every program should have the name of the program at the top. I believe in code reuse. Therefore, when you grab some code, identify the current name of the file. Identify who wrote the original code. Identify who has changed the code. Identify the purpose of the code - what it does, what, if anything, it expects as input, the environment needed to run it, the tasks it performs, and the outputs it produces. These minimal things ought to be in every piece of code, no matter how small, even if it takes up more room than the code itself!
Any code that either you or someone else might have to think about ought to be documented as well. Document each block of code. IF there are any lines of code that use some kind of optimization or shorthand, explain what you are doing and why.
Any good code really ought to be used, even if it was developed originally as a one time hack. Most of my good stuff can be copied and reused many times over. I like to remember what *I* did, but I also want to make my code usable for others. I sure appreciate it when someone else does the same for me.
Some code is more easily read than other code, but I maintain that no code stands completely on its own. Documentation provides a useful and important context and should never be minimized or ignored. However, that also puts the onus on the documentation to be useful, accurate, and relevant, otherwise it wastes more time and causes more problems instead of being a useful resource.
Brian Masinick, masinick at yahoo dot com Linux
what is that ..ok, i don't have a third line, neither i'm willing to count anything...
with geeks and haikus?
What about using,
//error
... debug code ...
if(!waddstr())
{
}
but it's a bad example as its a function you can look up.
i would use:
if(!write_to_window())
{// Returned false, failed to write to window
}
as it's clear what is does and allows you to debug easier
"In a time of universal deceit - telling the truth is a revolutionary act." - George Orwell
All that said, the amount you comment can be affected by your target audience. I wrote some C++ code that will be supported and maintained by people with little or no C++ experience, so I went to some lengths to comment common C++ idioms and constructs that I wouldn't normally do - as if I were commenting sample code for a C++ book, rather than commenting C++ code for someone with the same level of experience I have.
I, for once, have read TFA and I must disagree -that is why I do not read the articles often-. Comments must be written with the code, if you wait until the code is finished, then your boss will tell you something like "go ahead with the next chunk of code, we will add comments later (that means never)". And if the logic of the program is complex enough, it is probable that after finishing it (and more if there have been holidays in the middle) you have just begun to forget the scary details...
Why can't
Some comments I've written:
Here the purpose of the comments is to explain the math.
All code should have well-written comments. As Wirth pointed out years ago, people who can't express themselves well in their native language are generally poor programmers.
expected to understand
this */ haiku
(The classic comment was from the 6th Edition Unix kernel source, in a section that was doing context switches.) (Remember to pronounce "*" as "star".)
Bill Stewart
New Fast-Compression-only CPR http://preview.tinyurl.com/dy575ks
Could you comment that comment please? I am matrix math challenged.
Infuriate left and right
Fvck you Denis Krukovsky, and Fvck the editors for posting "articles" submitted by the authors of the linked content.
Were that I say, pancakes?
waddstr is a procedure, not a function
As far as I know, the difference is that procedures don't return values, and functions do. waddstr returns a value. What's the difference according to you?
And the compact waddstr name doesn't matter; if it were named window_add_string, I would make the same point by saying that its name would need changing to window_add_string_returned_error.
What I meant by "legacy" is one of those big ole' projects that lays dormant for years with lots of forgotten modules, no one actively involved with the code at their mental fingertips, when suddenly something stops working, leaving you scratching your head.
Slashdot entertains. Windows pays the mortgage.
/* FP! */
"If it was hard to write it should be hard to read."
First, comments are useful even if you are hiding your code forever. I can't tell you how often I've come back to an old piece of code, intended only for my own use, and been confounded by its obscurity or pleased to see an explanation in a comment. It makes a difference. It's also a good way to force you to think about what you're doing before you do it. (Even better are languages that allow you to express some of these things in the language itself, so that they are additionally checked by the compiler!)
Two: I'm surprised the article didn't explicitly mention pre- and post-conditions, since this has been known for years. When documenting a function, it's critical to state precisely the conditions under which it will work, what it does, and what state of the world it guarantees after being executed. Being specific here helps for the person who wants to call your function, but is even more important for blame assignment: when the program goes wrong, it's important to be able to figure out WHY. Is it the caller or callee? Being able to see that a function is called without its preconditions, for instance, would blame the caller. Seeing that the function doesn't meet its stated specification in a corner case would blame the function itself.
when the computer learns how to execute them.
So I use this fancy program that does it for you.
The Commentator
As per the subject line, the author of this article is on crack. I'm not going to argue the why's and wherefores of his text, but I have a major objection to his "when". He states that the best time to comment code is once it's all done, and you're just about to submit it. WRONG!
Has he ever worked on a major project? One that cannot be held in one brain in its entirety at one point in time? START with the comments. Start with the program architecture. Decide what each part will do. Write out how each part will accomplish its goals. Then, copy/paste that into your editor, and write the code to match the comments.
Believe me, if you can plan out how everything will work in the first place, and then just follow your plan, the whole project will be much easier. An added bonus is that the code comments just come straight from your design document. Of course, from the tone of the article, I'd guess that this guy's response would be "What design document?"
It may look like I'm doing nothing, but I'm actively waiting for my problems to go away.
--Scott Adams
What I often find annoying is that only program sourcecode is always allowed to contain comments, but many systems that store data do not allow comments with that.
Sure, the programmers that coded those systems must have been familiar with the concept of comments. And so, probably, are the designers.
Then, why can't I put a comment near a Windows registry entry, that explains why I changed it?
Or why can't I put a comment in an ACL or Group membership record that explains why a certain access is required?
There are many similar situations where you would want to annotate some piece of data stored in a file or database, but very often there is no such possibility.
He just says: "Fascinating."
Circumcision is child abuse.
In C, it's a conceptual difference. The return value of waddstr isn't important and in fact exists only because C doesn't have any other convenient way of indicating an error condition. waddstr is a procedure because it has side effects.
And the compact waddstr name doesn't matter; if it were named window_add_string, I would make the same point by saying that its name would need changing to window_add_string_returned_error.
The compat name does matter because it's exactly the point. Compact names make for hard to read code. And claiming that it should be window_add_string_returned_error just means that you are totally missing the point and don't understand the issue.
A function in C that can return an error condition is still a procedure. Consider it as being exactly equivilent to a procedure that throws an exception. Specifically, it's not returning a function result - it's using the value return mechanism to pass an error flag.
-- The act of censorship is always worse than whatever is being censored. Always.
Reviewing a piece of software today:
/* set the overflow flag to 1 */
.asm file and then add comments automatically. Like:
t->overflow_flag = 1;
Stupid moron! I can bloody well read that you're setting it to 1. WHY are you setting it to 1. What does 1 mean anyway? Jesus. And this code is supposed to go into anti-lock brakes.
My old prof for assembly programming used to get so sick of reading stupid comments he wrote a stupid comment generator. It would parse the
INC X ; add 1 to X register
Of course, none of the dumb students doing this got the joke. I guess to these people irony is what you add carbony to when you make steely.
K.
Everybody knows that good code is self documenting
But self-documenting code is not sufficient. It is very important but it's not an excuse to ignore comments.
A Government Is a Body of People, Usually Notably Ungoverned
Comment code by sprinkling examples:
... // Sname = "Joe User"
... // fSname = "Joe" and lSname = "User"
...
... // This regex makes sure fSname isn't '23skiddoo
... // nCount = 17 iff there are 17 people named "Joe User" in our database.
The idea is that people figure out the general from the particular better than they figure out the particular from the general. Learning goes in the reverse direction from math. First they see the pattern in the data then they begin to understand the abstract theme.
Source Code control system and IDE's need to invent a way to allow code reviewers and testers to comment the code, even when they are not allowed to alter the source.
Coding By Contract helps document things. So do assertions and Unit Tests. Executable comments, so to speak, are more believable.
Names matter. The more obscure the variable, the longer the name.
Fix slashdot to allow <code>, dang it!
I18N == Intergalacticization
I have never seen this mentioned, but my special trick for commenting
is to reference as much as possible the book or paper where I got the
algorithm. Many of us who have been graduate students have gotten
into the habit of obsessively referencing anything we have
written because we know the frustration of forgetting the source of a
particular fact. This should also be done with code.
An added bonus to this is that you have the book reference do the
documenting for you which will likely be better anyway since the original
paper can use fonts, symbols, greek letters, etc., to clearly express an
equation rather than just text.
Here is an example of my Free
Software FEA code.:
matrix using the QR with Wilkinson shift. It is taken from
the algorithms 5.1.3, 8.3.2 and 8.3.3 given in "Matrix Computations",
by Golub, page 216, 420, 421.
I have made a significant amount of optimization to take
advantage of the tridiagonal stucture of T.
Updated 9/2/00
SLFFEA source file
Version: 1.3
Copyright (C) 1999, 2000, 2001, 2002 San Le
The source code contained in this file is released under the
terms of the GNU Library General Public License.
*/
.
.
.
#define BIG 1.0e+12
#define SMALL 1.0e-12
#define SMALLER 1.0e-20
int matXT(double *, double *, double *, int, int, int);
int givens( double *a, double *b)
{
*/
double tau, c, s, fb, fa;
fb = fabs(*b);
fa = fabs(*a);
.
.
.
San Le www.slffea.com
He's used two stupid examples of commenting
Actual comment from actual production code:
return 1; # returns 1
L.
In C, it's a conceptual difference. The return value of waddstr isn't important and in fact exists only because C doesn't have any other convenient way of indicating an error condition. waddstr is a procedure because it has side effects.
errno's not exactly convenient, that I'll admit. Anyway, what does this then mean for functions/procedures for which either the side effect or the result can be important? For example, can Perl's map function be called a procedure when it's used as an alternative way of writing foreach?
I used to use Pascal, so for me, if you make a distinction between procedures and functions, if any value is returned, it's a function to me. If it's called for side effects, it's not suddenly a procedure, it's nothing more or less than a function with side effects.
The compat name does matter because it's exactly the point. Compact names make for hard to read code. And claiming that it should be window_add_string_returned_error just means that you are totally missing the point and don't understand the issue.
If waddstr is a function (which you don't agree with), the post I replied to basically said it should be named something like that. All I did was notice that that's what it said, and point it out in hopes of clarification (which I got).
Anyway, what does this then mean for functions/procedures for which either the side effect or the result can be important?
Such functions are generally poor practice. If you have to have one, name it appropriately. The awkward naming is probably a good sign that you're doing something wrong - a function called updateBalanceAndReturnInterest is something you should probably refactor. Note that perls map originates in functional programming, where side effects are prohibited, and using map to generate side effects is terribly bad practice. Of course, 75% of perls common idioms are terribly bad practice, and that is one of the reasons for it's reputation as a readonly language. If you're mapping values to other values, use map - that what it is for. If you're applying a method to a collection, use foreach.
There's a convention in C code, especially old C code, to make your function names as concise and non-literal as possible, that is a flaw (not in the language, but in the culture) and should be avoided. setWindowString is a much better name than waddstr.
Actually, it is a flaw in the language - or at least it was. For some time, there was no requirement for C compilers to treat anything more than the first n bytes of the function name as significant. At first I think it was platform-dependent, then "at least 8", and it grew over time. If you tried to have setWindowString and setWindowOnFire both, you could have a namespace collision. This influnced the standard libraries extensively, which in turn influenced most other C code for many years.
You're special forces then? That's great! I just love your olympics!
When I saw commenting classes in five minutes, I got excited because I thought it would tell me how to grade my student's papers more efficiently...
http://www.popularculturegaming.com -- my blog about the culture of videogame players
You're taking the OPs comment too literally and reading too much into them. Yes, the name of a function (note that the OP draws a distinction between functions and procedures - C doesn't have such a distinction, so you have to conceptualize a little)
I did, by assuming the meaning of "procedure" and "function" was the same as in a language which uses the keywords "procedure" and "function". Silly me.
should reflect what it returns. That does not mean you use a pseudo-hungarian notation and append the return type to the name, but that the phrasing of the name should indicate the return value.
That's what I did. Adding the return type would turn waddstr into waddstr_int. waddstr_error describes the return value.
isWindowRaised() returns a boolean. getSystemSettingsAsTree() returns a tree (but is redundant and should be called getSystemSettings if that is the only way to get system settings). Procedures (ie, functions with side effects) should be named by what they do, clearly. There's a convention in C code, especially old C code, to make your function names as concise and non-literal as possible, that is a flaw (not in the language, but in the culture) and should be avoided. setWindowString is a much better name than waddstr.
That I mostly agree with.
Such functions are generally poor practice.
I think there are legitimate reasons for it. Since you don't like the map example, how about C++'s new? (Admittedly, it's not really a function, but I think it makes the point clear enough.) Normally, its return value is important, but if your class manages itself, it may actually be reasonable to discard it.
Anybody who thinks we should rely on self-evident code instead of comments should look at the SQLite sourcecode. Every function has a clear, detailed comment which says nothing about how the function works, but does tell how it fits into the overall program. No amount of code restructuring and variable renaming will do what those comments do. It's the easiest-to-understand opensource code I've ever seen.
Dang! I thought the article would give me a surefire method to always write +5 Insightful comments...
D4mn3d college professors! Real programmers don't comment their code. It was hard to write, it should be hard to understand ;)
And in other news, Beatles Beatles has found the cure for cancer on the internet.....
No i'm not encouraging people who have variable/function names like "ArrayIndex" instead of "i" (they should be shot). Rules like he is encouraging cause people to call there variables "maxaddr" instead of "MaxPhysicalBusAddr" when you are a kernel programmer and it could be a virtual address, physical address, pci bus addresss offset etc... Variable function rules should read more like
I know this is a M$ hater web site but just about any programmer can learn a thing or two by picking up the "Windows Native API Refrence" and looking at the function names. They are usually pretty long, but its generally pretty easy to understand what they do, and what the parameters they take are. For an example of bad naming conventions just look at the linux kernel source which is full of evil shit for example (not the worst) http://lxr.linux.no/source/kernel/rcupdate.c
which has wonderful things like "call_rcu_bh()" "rcu_do_batch()". After you read the half page comment it makes sense, but some of this is just basic stuff. Plus about 50% of the functions in that module don't even have single line comment about what they do, any side effects, locking requirements to call etc...
I've seen this a lot over the years, but I thought it was actually a reincarnation of much earlier (pre-linux, maybe old mainframe era?) code with the possible explanation being that at that time it was originally written printers catching fire was a much more common threat than it is today.
:)
But...I could be wrong.
You can not document everything required to understand the code in the code itself. Sure, it must be easy to read and comprehend but the self documenting stops there. There always be some aspect you can not put into the code.
My favorite comments is
Seriously, comments must be added if the time spent writing them is less than the time which will be gained trying to understand the code.I had a friend ask me to help him fix a bug in an open source program so he could make it run on his system. I downloaded the code and it didn't have any commenting anywhere in the entire project. I couldn't even figure out where to start looking for the bug. Similiar to my very early complex programming projects. I had to reread the code completely to figure what some of the functions did. I also ended up commenting as I went.
A good comment is one which is written for its readers.
Soviet Russia
"Season mention" comments you
In Winter: Profit
I remember sigs. Oh, a simpler time!
Summer has ended
Portman sitting in hot grits
Alas, never be.
The season is put
In the opening stanza
Excellent effort
Lost at C:>. Found at C.
//
//
//
//
Midn, is that you?
I haven't seen you in like 30 years!
How've you been?!
You know where you are? You're in the $PATH, baby. You're gonna get executed!
i've thought about this. but there's a whole subset of sarcasm which, even in spoken language, is entirely deadpan and doesn't have any indicators of sarcasm.
(I think this is the part that Americans have trouble with)
my password really is 'stinkypants'
I am an old school coder, and I see a lot of this stuff these days:
// Bleah
// Bleah
// Bleah
// Bleah
// Bleah // Bleah // Bleah // Bleah
if (foo) {
}
Why do people put the opening bracket on the same line as the conditional? where the hell did this come from? I see it a lot in JS, and more modern C/C++ code. I always though you were supposed to use carrage returns and tabs to make it easy to see the body of a conditional:
(underscores for whitespace; damn you slashcode!)
if (foo)
{
_____
_____
_____
_____
}
Did I miss something? Are all the 'cool' coders doing this now, and I'm just old?
HA! I just wasted some of your bandwidth with a frivolous sig!
For I Equals One
To Four Hundred And Twenty
Do Function, Next I
----- Concentrate on promoting more than demoting.
Code should be self documenting because humans are bad at maintaining redundant things. Code and comments tend to diverge. You either spend time being very careful to update both the code and comments, or you spend time discovering that the comments are out of date.
Keep in mind that "code should be self documenting" is a rule of thumb, not an absolute law. Commenting something that is cryptic by its very nature is a good idea. Documenting the interface to a function is helpful. "Code should be self documenting" isn't lashing out against documentation and comments as a whole, it's lashing out against people who write clumsy, confusing code and slap some comments on as a fix. It's lashing out against people who comment on the "how" while completely glossing over the "why". Unfortunately proper commenting balanced with self-documenting code is frequently glossed over in course. Assignments require comments, but students are really graded on quantity, not quality.
Search 2010 Gen Con events
Perfect example:
"This is not a good comment"
Read Slashdot comments.
I comment my code pretty heavily, and I use one-liners all the time:
// A Buddhist at a hot dog stand said, "make me one with everything".
// If being a mother were easy, fathers would do it.
// I knew I was dyslexic when I went to a toga party dressed as a goat.
public static void main (String[] args) {
System.out.println ("Hello, world!");
for (int i = 0; i < args.length; i++)
System.out.println ("Hello, " + args[i] + "!");
}
}
etc.
Attack its weak point for massive damage!
Years ago, when writing lots of S/360 BAL, I'd often be able to use the following
comments for sections of assembler code:
go forward,
move ahead,
try to detect it,
it's not too late
to whip it
whip it good!
These days, my favorite comment
is:
# Don't touch this unless you know WTF you're doing!
Which, of course, is no comment at all....
Here's my list of the MOST important things to make clear in code:
Of course, there are other things that could be valuable as comments, such as:
Obviously, I'm the kind of guy who thinks a short README.txt is infinitely more interesting than thousands of "x++; // increase x by 1" lines...
If you can't even understand what some code is supposed to do, or why anyone would want to do that, then you really have a problem understanding the code. And to tell you the truth, it happens pretty much all time for me... While a program might have a documented purpose, an individual class, or even function or method has a documented purpose, very often you will have to dig pretty deep before you even find out the major components and interfaces of a big program (I.e. which files should I hunt in for changing how part foo behaves...).
I like to make my comments interesting by inserting snippets from bash.org, keeps the code reviewers occupied... /*
what is wrong with slashdot.org?? I am almost done reading my 1997-2001 Slashdot.org cache CD-ROM set, if I finish and its not back up, I may perish
*/
Task Mangler
No #
I think I'm getting my Ws confused here. How would you differentiate the Why and the What of code? Right now I'm thinking that the What is plain-English pseudocode. Would you agree?
Computers are useless. They can only give you answers.
-- Pablo Picasso
I always am interested in seeing different styles as far as commenting. I've read some interesting things here. I figured I'd share an example of my own style:
http://hobbit.ninebit.org/commentexample.html
I think that most people will probably find this all way too verbose. It suits my needs well though. I've been using it for years. Once you get used to it, it isn't too bad to write, and it's very nice on the reading side.
I put comments at the top of the file explaining what is included and why you would include or run the file (depending on if it's an app or a library.) This is so that I know right when I open the file what I'm about to read. I include a list of authors here so that you know who to go to with questions. I do *not* include the date or any other information that is either useless or can be found by looking at the properties of the file itself.
I put comments at top of classes explaining what they are for in context of the entire application/library. This is so that when I locate the class I know exactly what it's for and how it fits into the grand scheme of things.
I put comments at the top of methods explaining what they are for in context of their class. This is so that I know exactly what a specific method is for.
Occasional decorated grouping comments to provide easy visual navigation of the file.
Most of these comments don't fall out of date too quickly by nature of *what* is commented (purpose)
Beyond that:
A good editor will give you the navigational tools you need to find your way around a good bit of code and visualize the class structure a bit.
A good source control system will give you all you need in terms of modification notes, dates and authors. The only reason that I keep the author list in the source file is for convenience, and because it's one of those things that if it gets out of date it's not really a huge deal.
Well, it's the linkers that have the problem really. Blame IBM and their poxy 6 character limit on function names for mainframes for much grief. I'm annoyed at the current (modern) linker I am using which has a 32 character limit, which is very annoying for generated labels (coming from filenames from content creators).
No comment.
If it is obvious from the code, your project is too simple.
(Flippant, but not totally false. I work on research code that does...significantly complicated things. It can be hard enough for me to keep track of the interactions of the algorithms even when I'm designing them on paper; translate them into code, and the result is not at all trivial.
What my code does can be hard to understand when I've made a serious effort to clearly explain what it does in prose; even then, I expect understanding what it's doing to require effort from other researchers in my subfield. To expect any of them---much less a more junior researcher---to understand what is going on from the code alone is simply nonsensical. They would dismiss it as a waste of their time, and rightly so.
If code were that easy to read and understand, it would be found in most computer science research papers; that such papers avoid it like the plague suggests that's not the case, even for less-complicated problems.)
A Leaf falls to remind
the rule for Haiku is
Kigo for season on first line always
--- Sorcery
A common experience for me is that my understanding of my classes and their true purpose changes overtime. This of course means that my comments must change if they are to keep up with my code. This means that I must rewrite a lot of comments which is really throwing away work...something I hate to do. A lot of times I know that a class will change as my understanding of it's role becomes clearer when I code other classes with which it will interact, so I purposely hold off on commenting until things become clearer. Unfortunately, following up doesn't happen as often as I wish. I know we are supposed to understand everything up front before we start coding, but that's just not realistic and a lot of important insights occur while coding. So I'm currious to hear how other /. handle this issue.
In general, Pike's essay is too general to be specifically useful.
However, I believe this is the smartest thing he says in this essay:
Of course, it has nothing to do with commentsI had forgotten how much cooler teenagers look when they are smoking. Oh, wait
You proved me wrong :)
my password really is 'stinkypants'
The WHAT:
// open file ... some code // read header ... some code // read contents ... some code // close and finalize ... some code
:D as the programs comments only tried to explain the syntax or semantics of the -- for me -- new language. So indeed stuff like: i++; // increment i where written there and I did copy that style for a while (20 years ago, ofc).
For a class 2 or 3 sentences about WHAT the class is doing should eb sufficient. Similar for methods one sentence of comment WHAT the method is doing should eb enough.
I only use more than the reccomendation above if a non obvious design pattern is involved.
I (and most in my company) don't comment set/get methods. Except there is something special to know about.
The WHY:
I coment stuff that looks unusal, e.g. a typical for loop goes from 0 to n - 1, to iterate over n items. But some times you start at 1 or count up to n or count to n - 2. WHY? Thats worth a comment imho!
If the flow of a method is not obvious I might add a one line comment above a section like:
{
}
However in such a situation its more appropriated to refactor the complete method to call private helper methods:
{
file = openFile();
file.readHeader();
file.readContent();
finalizeAndCleanUp();
}
And now: you don't need any comment at all.
My background:
I learned commenting from books teaching programming languages. And I have the opinion most people did.
That was stupid
Such a comment is of course complete nonsense if you know the language.
Regards,
angel'o'sphere
Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
I would like to see somebody attempt to write code using Iambic pentemeter... hahaha Good code should be easy to read, stupid coders should be beaten over the head...
Haikus are poems
with seventeen syllables
in three lines of verse