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
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 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");
}
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.
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...
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.
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
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
"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.
© Leo Plotkin
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/Avantslash - View Slashdot cleanly on your mobile phone.
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.
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...
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.
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.
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?
"Good code" will be easy to read AND have good comments. For example, my company has some old SQL Reports that need to be maintained on rare occasion. I can kind-of-sort-a make out what the code is doing, but I am not used to that syntax and I havn't been able to find any tutorials for the stuff on the web anywhere. It sure is nice to have comments along with the code that I can read in english what the code is doing. "This will print the subtotals","This pulls the exchange rate", etc. Does that make it a bad programming language? Probably, but it still has to be maintained. Life sure would be alot more difficult for me if the original programmer of those old reports had thought that comments were a waste of his time.
There's no place like ~/
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
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.
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.
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.
"If it was hard to write it should be hard to read."
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
> Yeah Taco, I remember the big green book too. Thanks for giving me flashbacks!
What is this 'ADA' you speak of? American Dental Association? Americans with Disabilities Act?
The programming language is called 'Ada', as in Ada, Lady Lovelace, Charles Babbage's sidekick.
Sheesh, evil *and* a jerk. -- Jade
Soviet Russia
"Season mention" comments you
In Winter: Profit
I remember sigs. Oh, a simpler time!
//
//
//
//
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 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!
basic programming classes seem to push overcommenting.
good comments should imo cover
1: the why (why am i doing it this way)
2: the why not (why am i not doing this the obvious way)
3: the high level what (though to some extent this can be pointed out through method signatures etc)
4: the low level what in cases where it wouldn't be obvious to someone reasonablly skilled in the language.
However you don't get many of those in trivial programming excercises but the teachers are still supposed to encourage people to use comments. So naturally comments that point out trivialites are the result.
note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
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.)