Page 1 of 2

Commenting Code

Posted: Wed Jun 01, 2005 10:52 am
by CloudNine
Lo guys,

Just to start up a thread of conversation, how and when do you guys comment code? I tend not to bother most of the time, because I'm generally the only person looking at the code, although when I'm stuck when coding my OS, I generally go through and comment stuff that I wouldn't comment otherwise (internals of the PIC for example :)).
What are your thoughts? (and is there any way to discipline myself into commenting?) ;)

CloudNine

Re:Commenting Code

Posted: Wed Jun 01, 2005 12:39 pm
by Curufir
I tend to over-comment myself (Practically any non-trivial line of code gets a comment) as a side effect of how I program. I pick up a project, code like crazy for a short time, then stop coding and go back to design or another project. A cycle which results in me having quite long periods between working directly with the code.

I didn't use to comment much at all and wasted quite a bit of time staring at code after starting to work with it again, trying to figure out what I was thinking when I wrote it.

Guess I just fell in to my over-commenting style as a way to help myself get familiarity with the code back quicker. Works quite well for me, although others might find it annoying.

Re:Commenting Code

Posted: Wed Jun 01, 2005 1:30 pm
by Colonel Kernel
I approach "hobby" coding the same way as my projects at work -- design everything first, then code later. The comments become part of the design process. I take a detailed design (usually UML diagrams and some accompanying docs) then create shells for all the classes/functions etc. Then I will document those shells (using Doxygen in C++, XML comments in C#, etc.) so that I know what each functions is supposed to do, what its parameters/returns/exceptions are, etc. Then I write the code. :) Because each function signature is so well commented and functions are usually very short, there is little need for comments in the body of each function unless they do something tricky.

Coding should not be a very creative process, IMO. It should be like hammering nails, not writing blueprints.

Re:Commenting Code

Posted: Wed Jun 01, 2005 4:08 pm
by mystran
I tend to comment code when it could be unclear why something is done where (or how) it's done. Examples (from real code of mine, unedited) follow. After each sample is additional comments about it.

Code: Select all

    // sin, except basic period is [-0.5, 0.5]
    double Msin (double x) const {

        x -= rint(x);
        x *= 2 * M_PI;

        // this is basic 7th order Maclaurin for sin(x)
        // and it's quite accurate at [-Pi/2, Pi/2]
        // and more or less decent at about [-Pi, Pi]
        //
        double x2 = x*x;
        return x*(1+x2*(-1+x2*(1-x2*(1.0/42))*(1.0/20))*(1.0/6));
    }

Ok, first of all, the first comment is important, because otherwise you'd get the period is what real sine has. If somebody thinks they could figure out where the function came from without the second comment, then they should be doing maths and not CS.

Code: Select all

    // some bogus value, any bogus value will do.. just bogus enough ;)
    height.last_x = height.last_y
        = light.last_x = light.last_y
        = blend.last_x = blend.last_y = 0xDEADBEEF;
Seriously, that comment probably explains something. Now that I think of it, it probably SHOULD tell WHAT kind of value is "bogus enough". Then again, I think that if someone wanted to change that value, that someone would understand the relevant piece of code well enough to know what to do.

Code: Select all

            // If XMODIFIERS is not set, we probably want to
            // use X Servers internal translation instead of
            // "none" which would default.
            if(getenv("XMODIFIERS"))
                XSetLocaleModifiers(""); // failure is non-fatal..
            else XSetLocaleModifiers("@im=");
The first comment tells why we actually bother, and saves an API check by telling what we do. The second small comment saves another API check by telling that we ignore return values because it doesn't really matter.

Code: Select all

        // These two friends manipulate the "parent" attribute.
        // They would be Container's members if that wouldn't cause
        // unfortunate cyclic definitions.
        friend void Container_add(Container *, Component *);
        friend void Container_remove(Container *, Component *);
Another comment that tells something non-obvious. In this case we tell the reader not to bother trying to "fix" it.

Code: Select all

        // seems to be needed on x86, probably endian dependant..
        png_set_bgr(png);
This comment tells the reader that the line has a purpose, even if that purpose might not have been 100% clear when the line was added. It also kinda warns a future debugger that there might be something dubious here.

Code: Select all

        return 0; /* should not be reached !! */
Classic. Tells everyone that the return there is just to get rid of a compiler warning.

Ok, so I hope this set of examples was wide enough to give you people an idea of what I comment and how.

Re:Commenting Code

Posted: Thu Jun 02, 2005 12:05 am
by Solar
There's a sentence in my head that defines my commenting style:

Source tells you the *how*, comments tell you the *what*, documentation tells you the *why*.

Uncommented code is a royal pain in the backside. No matter how "clear" and "logical" you thought it is when you wrote it originally, without comments it is just that much harder to maintain it afterwards, as the maintenance programmer likely has a different way of thinking, not the same amount of background knowledge, and is usually in an awful hurry to fix your bugs.

Since there is a bug (or he wouldn't bother with your code), the code does not reflect what you intended to do - so a comment that (not-so-) redundantly states what the code is supposed to achieve can be of invaluable help to locate where you screwed up.

That's why I comment religiously.

Aside from the usuall add-on comments ("// TODO: ..." and "// FIXME: ..."), I add summary comments to functions and major code blocks that aren't trivial to read, so I can get the "big picture" at a glance and get to the piece of code I'm looking for quickly when reading my code later on. (I.e., "I have a problem with the output handling... which part of the code is it... no... no... no... ah, here it is. Now, *how* did I do it...)

I also add comments whenever my initial, intuitive solution didn't work out, to explain why the obvious doesn't work. Keeps those coming after me from making the same mistake again.

Re:Commenting Code

Posted: Thu Jun 02, 2005 12:37 am
by distantvoices
I usually don't comment every little line of my code - it remains rather uncommented in the function blocks, except for small mile stone remarks -> because, see, if I'm about to write something tricky or big, I tend to split it up in smaller tasks (to avoid big functions - but never the less, some GET big), and before I actually code, I sketch on a sheet of paper in order to get it sorted out right. Then I write some comments about: what is the function supposed to do. How do the steps we take to get the task done look like in a few sentences - like step 1, step 2, step 3.

then, in the code, there comes only a small //step1 ... in order to sort the tricky things out easier.

This style of commenting is evident in both the file service and the gui service.

I don't comment list manipulation functions. They are so common knowledge ...

Well - the same style I follow for my business coding too.

And as Solar states, a //FIXME on a strategic place is often asked for coz after 8 hours of work I for one don't remember exactly where I have stopped the evening before - or the week before, if time didn't allow for code churning sessions.

So, in short, for me, the comments are reminders, walkthrou's and hooks for adding stuff and ideas.

and don't shy away to make brainstorming comments at places where you think they are appropriate. Fixing an idea keeps it caught in the nifty trap of the written word. *gg*

Re:Commenting Code

Posted: Fri Jun 03, 2005 7:05 am
by NOTNULL
I don't spend my precious time in commenting my code, while coding. When I feel a bit tired after coding (not too long), i start commenting the code. I usually comment everything in my code (even a simple logic), because, i forget everything after coding ;D.

Re:Commenting Code

Posted: Fri Jun 03, 2005 8:44 am
by df
i started throwing commets into everything.
my editor has a htokey which will drop a /* */ and position the cursor in the middle, so i just hotkey type comment.. just the fact its built into the editor makes me comment stuff where before i didnt bother. now i write a line or two and comment everything under the sun.

Re:Commenting Code

Posted: Fri Jun 03, 2005 4:49 pm
by mystran
I will now claim that over-commenting is a bad idea, and I'm also going to throw an argument that I haven't heard, and which I think is better than any of those I HAVE heard:

If you use too many comments, the very presense of a comment no longer signals anything. If you use comments only when they actually have (at least some) real value, the reader will be alerted by the very fact that a comment exists.

Also, for this purpose I use not only TODO and FIXME, but also

Code: Select all

   /* NOTE: this is important information that you absolutely
    * must read before you attemp to decipher my code.
    */

Re:Commenting Code

Posted: Sat Jun 04, 2005 4:48 am
by Neo
I usually comment after I get a piece of code working the way I want it to.
As soon I find that it works as expected then I start the commenting which has sufficed (so far at least ) ;)

Re:Commenting Code

Posted: Mon Jun 06, 2005 7:45 am
by ark
Having gone through a "comment everything" phase, I've come to realize that it has a tendency to make code less readable, not more readable. In general, well-structured code with short functions and descriptive variable names (specifically not over-abbreviated ones) can be read without them.

You absolutely should comment functions/methods and classes to give an overview of how they are used...functions in particular need comments to tell their pre- and postconditions, return values, etc. No one should have to look at the code for your function to use it, only to modify it.

In general, any time you have a group of statements that are working toward a particular goal but it takes more than a few statements to get there, you should comment the overall goal and leave the code to specify the details, with the one exceptional case being if the details are particularly tricky.

I tend to write code first and then comment later, which I'll readily admit isn't all that great a habit.

Re:Commenting Code

Posted: Mon Jun 06, 2005 8:15 am
by Solar
Joel wrote: In general, well-structured code with short functions and descriptive variable names (specifically not over-abbreviated ones) can be read without them.
If your code couldn't be read without comments, you're in deep trouble (or coding Perl, APL, Brainfuck, or LISP). ;)
You absolutely should comment functions/methods and classes to give an overview of how they are used...functions in particular need comments to tell their pre- and postconditions, return values, etc. No one should have to look at the code for your function to use it, only to modify it.
98% ACK.

But to modify your code, you have not only to read it, but understand it. If a piece of formula munching is intended to to a Newton approximation, why not add a note that it's a Newton approximation to the loop? It makes reading so much faster, and just in case your code doesn't do it right, the maintenance coder might have an idea what it should do (a Newton approximation) - instead of looking at a piece of maths that might or might not do what it's intended to do.
In general, any time you have a group of statements that are working toward a particular goal but it takes more than a few statements to get there, you should comment the overall goal and leave the code to specify the details, with the one exceptional case being if the details are particularly tricky.
Yep. But sometimes a single statement can be sufficiently complex to warrant a comment. Perl regexp's, for example.
I tend to write code first and then comment later, which I'll readily admit isn't all that great a habit.
A catching maxim is, "comment now because later never comes". ;)

Re:Commenting Code

Posted: Mon Jun 06, 2005 8:55 am
by Candy
I comment things I consider useful. That is, comments for classes that aren't immediately obvious (class Image won't get any comments), algorithm steps for nontrivial algoritms (all algoritms that deserve a name get comments for each step, so you can use that knowledge in reading the code), comments for functions with dubious use or weird calling conventions (occasionally I make some that modify a parameter instead of return a value etc.

Never overcomment.

Re:Commenting Code

Posted: Mon Jun 06, 2005 9:58 am
by Joel (not logged in)
But to modify your code, you have not only to read it, but understand it. If a piece of formula munching is intended to to a Newton approximation, why not add a note that it's a Newton approximation to the loop? It makes reading so much faster, and just in case your code doesn't do it right, the maintenance coder might have an idea what it should do (a Newton approximation) - instead of looking at a piece of maths that might or might not do what it's intended to do.
I was using the word "read" in the sense of both picking out the syntactic structure and understanding what the code is doing :)

I completely agree...if you're implementing a well-known algorithm, then document it as such. Similarly, if you find an algorithm on the Internet, give a URL for where you got it from.
Yep. But sometimes a single statement can be sufficiently complex to warrant a comment. Perl regexp's, for example.
Yeah, it's not a rigid rule. Most of the things I was saying were more general guidelines. I've never programmed in Perl, so I don't know the details of what it requires, but in C, C++, or Java programming, I would tend to say that if a statement is complex enough to need to be commented, then it should be more than one statement, anyway. I'm sure there are exceptions to this (meaning that there are times when this would actually hinder readability instead of helping it), but I would say in general complex statements are the less readable alternative.

Re:Commenting Code

Posted: Mon Jun 06, 2005 4:09 pm
by mystran
Solar wrote: If your code couldn't be read without comments, you're in deep trouble (or coding Perl, APL, Brainfuck, or LISP). ;)
Perl, APL or Brainfuck.

Lisp is one of the most readable language once you learn to ignore the parenthesis and read by the indentation instead.. which is fine because indentation is pretty much the only thing Lisp programmers do not have differing opinions.

Ehmm... ignore what I just said.
98% ACK.

But to modify your code, you have not only to read it, but understand it. If a piece of formula munching is intended to to a Newton approximation, why not add a note that it's a Newton approximation to the loop? It makes reading so much faster, and just in case your code doesn't do it right, the maintenance coder might have an idea what it should do (a Newton approximation) - instead of looking at a piece of maths that might or might not do what it's intended to do.
I can see that you have never visited a mathematics class (of any level from elementary to undergraduate at least), because otherwise you'd know that the best way to teach mathematics is to show someone several mystical formulas of incomprehensiveness +5, and assuming that by looking at them long enough one suddenly learns something about mathematics.

The alternative explanation is that you are a cruel person and want to deprive your fellow programmers from the wonderful feeling of enlightenment when they finally... hmmh.. learn to hate mathematics.
Yep. But sometimes a single statement can be sufficiently complex to warrant a comment. Perl regexp's, for example.
I always though the regex were the only readable part in Perl.