How to Write Comments 556
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.
Reading (Score:5, Funny)
Re:Reading (Score:5, Funny)
Code should read easy
Like many Slashdot comments
See? It's not so hard.
MOD PARENT UP. (Score:2)
Re:MOD PARENT UP. (Score:2)
Re:Reading (Score:3, Funny)
Carelessness surely follows
Always preview first
Re:Reading (Score:5, Funny)
Then rewrite it correctly
Get double karma
Re:Reading (Score:5, Funny)
My haiku is rotten
I hang my head in sorrow
Forgot the season.
Re:Reading (Score:5, Informative)
For anyone not getting this, a traditional Haiku always contained references to the season [big.or.jp].
indeed, but to be both traditional & slashdott (Score:3, Funny)
"Season mention" comments you
In Winter: Profit
Re:Reading (Score:3, Funny)
winter of our discontent.
Hell freezeth over.
Re:Reading (Score:5, Funny)
But funny gets no karma
Snow falls slowly here
Re:Reading (Score:5, Insightful)
And the code should tell you how
Comment tells you why
Re:Reading (Score:3, Interesting)
How many times can we see a line like this... that's just writing comments without any reason.
I prefer function header comments which describe what the piece of code as whole does. Not everyline, as teachers say it should be done.
Re:Reading (Score:5, Informative)
Having one-liner comments all over the place makes comment maintenance more troublesome and can distract from actual comprehension of what is going on while reading the code, particularly when there are bits of orphaned antique leftover comments. A single comment blob before a function or large code sections tells the reader about the spirit of code to come without interfering with reading beyond there and makes it easier to maintain comment coherence when changes are made.
For more convoluted code, I often add blobs before major loop/switch/etc. too - adding comments while I write these things takes less time than what it may take me to re-read the code until I remember exactly what it does and how. (inputs, outputs, side-effects, etc.)
Re:Reading (Score:5, Insightful)
I know this is a religous topic, but I personally would say that old, left-over comments are simply bad practice. Well-maintained comments and well maintained code are the ideal solution. I don't think there's any excuse for not updating a comment which is right there, in the code you're about to change.
I've suffered from antique comments, and also no comments; IMHO, they are both as bad.
Feel free to flame me now
Re:Reading (Score:3, Funny)
Great, I'm sure this Howard-Cosell running commentary is cute if you already know what the code is doing, but it means nothing to everyone else. Comments are not for you, they are for other people.
Question for all the coders out there.. (Score:3, Insightful)
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)
{
_____
_____
_____
_
Re:Question for all the coders out there.. (Score:3, Insightful)
It lets you get the whole example on the page in a font that is readable from the back of the lecture hall.
Personally, I prefer it like this. The opening brace on the line with the conditional (for, while, if, etc), the conditional block indented, and the close-brace at the same indent as the start of the conditional. I tried a few other ways*, but didn't like them: they weren't readable e
Re:Question for all the coders out there.. (Score:3, Insightful)
> Why do people put the opening bracket on the same line as the conditional?
You must not be very "old school" if you don't know the answer. The cuddled braces are the original K&R indentation style; they are what C was supposed to look like.
Another answer is that there are two different ways to look for blocks. I look at indentation as a clue to the new block and when I see a brace on a line by itself I immediately interpret it as:
if (x);
{
}
This is especially true when I c
Re:Question for all the coders out there.. (Score:3, Insightful)
Re:Question for all the coders out there.. (Score:3, Informative)
<disgruntled 1024x768 coder>
How big a deal it is depends a lot on the kind of code you're writing. If you've got lots of small ifs, tight loops, and small functions, the braces *do* take up a significant chunk of screen real estate.
</disgruntled 1024x768 coder>
Re:Reading (Score:3, Informative)
One helpful practice I picked up (see Code Complete, Steve McConnell) was to design functions in advance and use the design a the comments.
eg
function foo()
{
}
Are you certain this is what you want? (Score:3, Funny)
{
System.IO.Stream stream = System.Net.HttpWebRequest.Create("http://www.goats e.cx/receiver.jpg").GetResponse().GetResponseStrea m();
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(stream, false);
stream.Close();
System.Windows.Forms.Form form = new System.Windows.Forms.Form();
Re:Reading (Score:2)
Comments (Score:5, Funny)
<!-- why don't they ever RTFA? -->
<b>Nothing for you to see here. Please move along.</b>
Re:Comments (Score:5, Funny)
This is my comment. There are many like it, but this one is mine.
My comment is my best friend. It is my life. I must master it as I must master my life.
My comment, without me, is useless. Without my comment, I am useless. I must author my comment true. I must write clearer than my code which is trying to obfuscate my efforts. I must comment in before it gets me fired. I WILL...
My comment and myself know that what counts in this job is not the lines we write, the size of our file, nor the time to compile it. We know that it is the completed change requests that count. WE WILL COMPLETE...
My comment is human, even as I, because it is my life. Thus, I will learn it as a brother. I will learn its weaknesses, its strength, its words, its letters, its punctuation and its opening & closing tags. I will ever guard it against the ravages of re-edits and cruft as I will ever guard my legs, my arms, my eyes and my heart against damage. I will keep my comment clean and ready. We will become part of each other. WE WILL...
Before God, I swear this creed. My comment and myself are the defenders of my department. We are the masters of our code. WE ARE THE SAVIORS OF MY LIFE.
So be it, until the beta goes gold and there are no further patch requests, but sales!
Re:Comments (Score:5, Funny)
// I guess I should have used one-liners.
Haiku Commenting? (Score:5, Informative)
Re:Haiku Commenting? (Score:4, Insightful)
When there aren't comments, it is hard to figure out what parts of what do which.
What parts do what should be clear from the names of function calls and variables, but whenever a function becomes longer than something really short, yes, it needs comments describing what happens where. If a function does something complicated, it's worth starting with a comment describing pre- and post conditions.
That said, before you add a comment, first check if you can make the various identifiers any clearer. And then still add the comment, unless it's suddenly become really stupid.
Re:Haiku Commenting? (Score:5, Informative)
Now there is an excellent idea! It doesn't take a lot of effort - you should be able to come up with some basic constraints on inputs and outputs if you have any decent idea of what the function does - but it is very helpful documentation to anyone else, particularly for people who have to call the function (as it clerly delimits exactly what they need to provide, and exactly what they can expect to get back). Better yet, as long as you use a system that supports it you can get a whole lot of benefits in terms of automated checking and debugging of your code, saving you a lot of effort later.
Eiffel [loria.fr] and D [digitalmars.com] support pre and post conditions directly in the code (instead of in comments). Java has JML [iastate.edu] which is a syntax for writing pre and post conditions in comments, as well as some tools to do extra checking, add runtime checks to your code (or not) based on the conditions, write the conditions into JavaDoc properly, and automatically generate JUnit tests based on the conditions. If you program in Ada there's SPARK [praxis-his.com] which supports pre and post conditions as comments as well as a range of other annotations, and provides extremely powerful tools to do extensive static checking and analysis and even generate automatically simplied proof obligations based on your annotations. If you program in Python there's PyContract [wayforward.net] which allows you to write pre and post conditions into docstrings and switch on or off runtime checking of those contracts. I expect there are plenty more, so hopefully other people can mention those.
Jedidiah.
Re:Haiku Commenting? (Score:3, Informative)
I didn't know about that one (mostly because I haven't really done any Perl programming in quite a while) but you're right, it is pretty slick. I like it. definitely a must next time I end up doing any OO Perl.
Assertions have long been a part of C and C++ programming, of course, but that's not really designing by contract, so much as performing error checking. These are dif
Re:Haiku Commenting? (Score:3, Insightful)
Re:Haiku Commenting? (Score:5, Insightful)
In short, comments convey concepts and explanations, not mechanical descriptions.
Re:Haiku Commenting? (Score:5, Insightful)
It's not uncommon for my code to do something really non-obvious to accomplish a task in a more efficient way. Processing sensor readings, for example - on a PC it'd be a simple floating point math operation. On the chips I use, the floating point library would itself fill the entire available memory. Instead, I wind up with a bit of hard-to-read code that accomplishes the same thing using the shift and multiply operations the CPU is good at. For my own sanity I leave very specific comments about what's going on and what the equivalent calculation is.
Re:Haiku Commenting? (Score:5, Funny)
The 2nd rule of software engineering is: you DO NOT put hacks your projects
The 3rd rule of software engineering is: document you hacks
The 4th rule of software engineering is: one hack at a time
The 5th rule of software engineering is: if this is your first project, you'd have to do lots of hacks.
Re:Haiku Commenting? (Score:3, Funny)
A bad question... (Score:2, Funny)
Let the commencement of the comment posting beginulate!
cenqua! (Score:5, Funny)
The Commentator [cenqua.com]
Just be careful on your settings and you should be fine.
Re:cenqua! (Score:4, Funny)
Check out Rob Pike's thoughts on code commenting (Score:5, Informative)
Comment removed (Score:5, Insightful)
Re:Are you reading the same thing I am? (Score:3, Insightful)
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
Re:Check out Rob Pike's thoughts on code commentin (Score:3, Insightful)
This is one of the most effective methods of producing self-commenting code and I wish everyone writing programs would do this.
Good code is self documenting... (Score:5, Insightful)
Re: Good code is self documenting... (Score:2)
Re: Good code is self documenting... (Score:2)
The best way to code + comment is to write out the algorithm or steps of a function using comments, and then fill the code in. Good commenting is a bit of an art, and definitely takes a while to learn more through experience than instruction.
Re: Good code is self documenting... (Score:5, Interesting)
Here's the original code:
L = Cholesky(cov0);
th1 = L.i() * th0;
lrt = (th1.t() * th1).Trace();
which is supposed to compute the same answer as the code:
lrt = (th0.t() * cov0.i() * th0).as_scalar();
I do agree that in general code should be self-documenting when possible, but sometimes you need a few lines of comments to explain a single line of code, or a few paragraphs of comments to explain a few lines of code. I added 17 lines of comments to that part of the program to explain 3 lines of code.
Re: Good code is self documenting... (Score:3, Interesting)
Re: Good code is self documenting... (Score:5, Insightful)
Self-documenting code is a wonderful thing, and greatly reduces the need for comments. Whenever someone brings this up, others say no, and eventually present an example such as yours: Entirely non-self-documenting. What the hell kind of variable names are those? L? a method named i()? Spell out "inverse" for gods sake! Of course you can't follow it. Hell, I know what Cholesky decomposition is, and I've read your explanation and I still don't know WTF that code is doing. I'll bet you needed 17 lines of comments. If you had instead changed the var names to something sufficiently descriptive, the code would successfully document what it is doing, leaving you to write a comment describing why; I suspect the third sentence of your post would have sufficed.
Re: Good code is self documenting... (Score:3, Insightful)
Obviously if you are writing some sort of a 3 tier application, which has a presentation, business and data tiers, then it is in fact possible to write good self documenting code, but you must also provide a design document, which explains how to read this code from high level point of view. But when you get into any specific details of that co
Re: Good code is self documenting... (Score:3, Insightful)
Even so, 'good code' is a combination of commenting and coding style. Probably, neither is sufficient alone. Even the most readable code will sometimes do things which are non-obvious or unintuitive, and comments, by themselves, cannot do near so much good as clearly, concisely, and well-styled code.
Comment every conditional branch or loop (Score:5, Funny)
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");
}
Re:Comment every conditional branch or loop (Score:5, Funny)
Re:Comment every conditional branch or loop (Score:5, Insightful)
Avoid 'magic numbers' too,
You've heard of constants?
Seriously, this is not good code: if (u & 0xFF1234) - what the hell is u? Is it the start of the file? What if your file structure changes, you want to grep for every instance of 0xFF1234 and see if it needs to be changed? What if you changed your definition of what a good file is?
Why not: if isValid(fileStart) - or if all you're doing is printing, just put it in the print statment? You do have to comment to explain why you're doing something, but the clearer the code is the easier it is to read and maintain.
Re:Comment every conditional branch or loop (Score:3, Interesting)
You've heard of constants?
Seriously, this is not good code: if (u & 0xFF1234) - what the hell is u?
Exactly. I was thinking the same thing.
Clearly labeled abstraction is self documenting and is just better.
Instead of if (u & 0xFF1234), why not have a macro like #define VALID_HEADER(a) ((a) & 0xFF1234) and use if (VALID_HEADER(u)). u might be an OK variable, maybe not.
One thing I do with perl code is instead of making a complex regexp that is expanded with inline commen
Re: Comment every conditional branch or loop (Score:5, Funny)
But be sure to put them outside the loop, so people won't have to read them over and over.
Re:Comment every conditional branch or loop (Score:3, Insightful)
// the only thing a comment here should explain is why you use & and not ==
if (uFileHeader & VALID_FILE_HEADER)
{
printf("File shares at least one set bit with a valid file!\n");
}
else
{
commenting made easy... (Score:2)
Dupe! (Score:2, Offtopic)
Oh... you meant code comments... never mind!
Sure (Score:3, Funny)
The why not the how (Score:5, Insightful)
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.
Re:The why not the how (Score:2)
if (Account.Tarrif == null)
return false;
Re:The why not the how (Score:4, Insightful)
What I see here isn't preventing an exception, but rather checking the validity of a paremeter. I know it adds extra processing, but so many problems could be avoided if programmers put more effort in to input (e.g. parameter) validity checks. If it's an unusual situation, check for it in an assert as part of the pre-conditions at the beginning of the function (programming by contract). I'm assuming this is Java code in your example - does it not support assert now?
Re:The why not the how (Score:5, Funny)
if (
Re:The why not the how (Score:5, Informative)
public bool CheckSmsValue(Account smsAccount)
{
And instead say:
public bool isSmsValueAccurate(Account smsAccount)
{
That way, anyone who glances at the call will know what the function does. In fact, the first one could be checking for existance, non-existance, accuracy, threshold, who knows? Heck, its exactly the kind of function that I could see being called in many different places by people expecting it to be checking different things. Or coder1 adds it in expecting it to check for "positive" as well as whatever else, months later coder2 realizes that it doesn't and adds the "extra check" into it - its a check function, after all, right? And then coder3's code in some far-away place suddenly starts failing because he didn't want that check in the function.
A good name should be an implict contract. The function above should, by that definition, return "true" if it did at least "check" the SmsValue, and "false" if it didn't bother to... not quite what the original intent was. Probably.
Phew. Sorry for the long-windedness.
Words to live by (Score:5, Funny)
"It was hard to write; it should be hard to read"
'course the profs didn't appreciate that much...
No (Score:2)
The classic (Score:2)
You are not expected to understand this (Score:2)
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.
Comments tell reason. (Score:5, Insightful)
Forget the comments (Score:2)
Why Comment in Haiku... (Score:2)
...when you can code that way?
"How to decrypt a DVD: in haiku form". [cmu.edu] It's quite elegant, really.
News? Matters? (Score:2)
Three Books to Read (Score:3, Informative)
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.)
Re:Three Books to Read (Score:3, Informative)
Comments First (Score:5, Insightful)
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.
Re: Comments First (Score:5, Insightful)
When implementing a big program or non-trivial algorithm, I start the file with comments that end up serving as an outline for the code I insert afterward. It helps clarify my thoughts about how I'm going to go about it, and of course keeps me from forgetting anything.
Re:Comments First (Score:5, Insightful)
That's some of the worst advice I have seen wrt. code commenting. Comments should never describe what the code does. If it is not obvious from the code, it should be refactored.
The strategy of verbose and essentially redundant comments are bound to end up in outdated and/or useless comments. If such a practice is employed in industry, forcing people to comment every loop, etc. as you describe, I'm certain there would be a lot of useless comments.
People will simply not do something, which they cannot see how they would later benefit from. Classic CSCW problem.
Re:Comments First (Score:3, Insightful)
It seems that most folks here believe that -- that you should only comment on why you're doing things, not what you're doing. But I think that's a bad idea. For example, let's say you've got some "code" that says:
I would contend that the comment should be "make a cake". I suppose you could contend that tells why we're combining the ingredients, but I think it's more clear to say that that is what we're do
Hard problems (Score:3, Insightful)
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 expla
Re:Comments First (Score:3, Insightful)
Haiku? (Score:4, Funny)
Begin declaring
Global integers, constant
As the winter rain
Check for null values
That will cause problems later
Cherry blossoms fall
One good reason (Score:3, Informative)
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.
Javadoc and XDoclet as models (Score:2)
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 ov
Definitely Haiku (Score:2)
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.)
/* Drunk -- fix later */ (Score:2, Funny)
Humour in the Linux kernel (Score:5, Funny)
'Why', not 'How' (Score:5, Insightful)
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.
Comments are Critical to larger scale projects (Score:4, Insightful)
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.
"should I write comments?" (Score:3, Insightful)
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
lazy programmers (Score:5, Insightful)
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.
Unified theory of commenting (Score:5, Funny)
My haiku (Score:5, Funny)
Damn! I wish I had mod points!
Better luck next time.
I have to tell this story... (Score:5, Funny)
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.
Overcomment everything (Score:5, Interesting)
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.
Article Author on Crack (Score:5, Insightful)
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?"
Re:Nothing beats good comments (Score:2)
Re:Nothing beats good comments (Score:2)
Re:Nothing beats good comments (Score:2)
My thoughts exactly. I can't recall how many times I've looked at sparsely-commented code and ran away in terror (or at least scratching my head). In my opinion it's essential to comment your code at some level. Finding that level is the hard part: you have to step back from what y
Re: ADA (Score:3)
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.