Fog Creek Software
Discussion Board




Commenting Code

I've been working on an application that includes comments such as, "This line causes some problems" and "There's a bug here... somewhere" and "Have to come back to this".  Suffice it to say that these are the only comments in the code.

At any rate, I was wondering if anyone had come across some interesting comments in the code they were working on.

I am also interested in hearing peoples - code commenting - habits.  Mine are'nt the greatest, but I'm improving.  I usually write a whole routine and then go back and comment the portions I feel necessary (which sometimes isn't much).  I know, it's backwards from 'textbook', but old habits are hard to break eh?

Dave B.
Wednesday, March 19, 2003

I always put a header at the top of a function that describes what the function will do in 1), 2) 3) format.  Then I add comments before each block of code within the function, starting with a repeat of the 1), 2) or 3) description from the header, plus any additional clarification that is needed.

It sounds worse than it really is.

Norrick
Wednesday, March 19, 2003

// drunk now, fix later.

Nat Ersoz
Wednesday, March 19, 2003

I only comment parts of code which are not intuitive.  Other than that, I neve use function headers, and only use short file headers with a filename (nice for printing) and copyright.

Big comments, when they merely state the obvious are incredibly annoying.  specially stuff like:

/*************************/
* function: foo()
* parameters: int x, int y, int z
* Description: transforms x, y, z with the foo function
/*************************/
int foo( int x, int y, int z ) { ...

I come across this kind of crap all the time in our vendor supplied code.  5 lines of wasted space in my editor.  --delete--

Nat Ersoz
Wednesday, March 19, 2003

My personal favorites:

#if HOST==WIN32 /* then you should shoot yourself in the head */

/* diddle things to screw up bandits */

// Ignore failure, it would be too much to deal with

Steven C.
Wednesday, March 19, 2003

Yeah,
I worked on code that had //FIXME blah blah blah... littered throughout the code.  Problem is some of the comments were over a year old and problems never fixed!  Take the time to fix the problem instead of leaving half done work.

Steven Tyler
Wednesday, March 19, 2003

I comment rather sparsely. If something is confusing, I comment it. I try to keep javadocing my current project, though I'm not so great about it. I just like having a linked web page with all my API on it. I use FIXME's, but only on things that are obvious what I should fix.

I would like to see a folding mode for vim that can fold comments in and out.

Mike Swieton
Wednesday, March 19, 2003

If you program in Java, IntelliJ's IDEA supports folding of javadocs, import statements and functions. I am not a big fan of IDE and tools but once I started using it, I can't go back. (before IDEA, I used EditPlus and the command line to do most of my development).

Natalie Ng
Wednesday, March 19, 2003

As a COBOL coder (yikes, and I'm in my early 20s!) I find most comments to be unnecessary, but I still put a header in at the top of every function.

When I sit down to code I draft a spec and plan all the functions I'll need, then I put in stubs, document the stubs, and call it a day.  The next day I fill in the code, which is relatively trivial at that point considering how most COBOL code follows naturally straight from the comments/stub description. 

And if my stubs and comments don't make sense to my decaffinated mind at 8am then they aren't sufficient and need to be fleshed out more.

Lou Brothers
Wednesday, March 19, 2003

I tend to be verbose with my comments. Functions are described in terms of purpose, parameter values and descriptions (plus input or output if I can't avoid it) plus return values. Certain variables assignments and declarations are explained because it won't be obvious without knowledge of a great deal of context. Comments are easier to read and more handy than technical documents which never get updated anyhow.

I think the better a program is structured, the easier it is comment - so very bad programs tend to have sparse comments. Just thinking about commenting can point out how wrong a certain sequence or arrangement is.

Although sometimes I receive a little criticism on the verbosity, I've never got a complaint from anyone who had to pick up my code. Handovers have been smooth, although perhaps I'm just a masterly skilled programmer =)

Commenting is an art not a science and the trouble is you rarely get feedback. One of the main reasons they are there is to help out other programmers when you're not there - which is usually when people want to curse you for bad commenting...

Joel Goodwin
Wednesday, March 19, 2003

I once was debugging some code and saw something to this effect.

/*
Dont touch this code, it is teetering on the edge.
*/

Matt Lee
Thursday, March 20, 2003

The only two types of comments that I use regularly are XML comments for generating documentation (C#) and TODO markers for things that need to be finished (which, shockingly, I do actually get back to).

I'm firmly entrenched in the camp that says that 99% of the time, when you're tempted to comment your code, you should be refactoring it instead.

Brad (dotnetguy.techieswithcats.com)
Thursday, March 20, 2003

SQL is in another class altogether. I despair over sparse comments in SQL, which is generally difficult to write neatly.

Not helpful:
/* get data */

/* update main table */

I'm happier if people can comment and organise sections of join criteria, which are usually the most difficult problem I have faced when reading SQL. I've had a far worse time reading SQL embedded in a series of stored procedures than I've had reading uncommented C code.

Joel Goodwin
Thursday, March 20, 2003

The most useful comments to me are those that capture information that can't be gleaned from the code. Given enough time I can figure out _what_ the code does.  I want to know 2 things:

1) Why the code is how it is.  "I used sockets instead of pipes here because..." or "I considered using a b+ tree here, but chose this instead because....".

2) What pitfalls should I avoid
"If you extend this function to support multi-mon, be sure to consider..." or "every time this function is changed, feature foo breaks. Beware!"

As a guide, consider what you'd tell someone who's taking over your code. Would you tell them "This function takes two parameters" or "wow, this function was a pain to write...I tried this, but then that broke feature X...."?

Color commentary is what I want. I can handle the play-by-play.

Malcolm
Thursday, March 20, 2003

I tend to write complicated functions by writing, in plain english, a set of steps I intend to do. Then I comment each step, and below this comment I write the code necessary for that step.

It's quite difficult to manage comments - during maintenance one might change code and not bother about the comments...to the extent that the comment is plain wrong. So I try to make my code readable instead - use Camel case, write descriptive function names, try splitting statements into sub parts that make more sense. Code complete by Steve McConnell (?) has some interesting tips.

Commented code is sometimes an issue - you tend to comment code while testing and write working code after it. Commented code looks like it can be removed without any problem - but it can be very helpful to the next person maintaining the code. Rule of thumb: If commented code needs to stay for maintence reasons, surround the code with a plain English comment giving a reason why. For ex. in one place I had to override a procedure and NOT call the inherited one, because the descendant did something funny. So the code went:

procedure TagClass.Something;
begin
  // DO NOT DELETE comments below. AND DO NOT DELETE
  // THIS PROCEDURE
  // inherited;
  // do not call inherited. It does <whatever>
end;

Deepak Shenoy
Thursday, March 20, 2003

I probably overcomment, but the product I work on is fairly large and I don't have more than a working knowledge of most of it, so when I have to go and fix a bug in code that is currently unowned (and which I probably won't be responsible for) I tend to be verbose in describing what I'm doing etc.

Of course, I also make sure to mention the specific bug # that I'm fixing near any code which fixes it, so later maintainers can easily see if something was put there for a reason.

In code I own and/or am newly generating, I like to do a comment block ahead of every function, generally with a single line description. Often, my function names would be adequate, but to satisfy my stylistic desires, I prefer to have a comment block in front of every function. I then tend to only comment as necessary -- to explain things which aren't immediately obvious, for instance, so that when I come back in 6 months I can immediately understand the purpose of this complicated string-twiddling loop.

Steve C.
Thursday, March 20, 2003

Sorry, can't resist the classic

http://kerneltrap.org/node.php?id=542

Juha
Thursday, March 20, 2003

I'd say my experience is in line with Steve C. I generally work on large projects during which I see lots of code that I am completely unfamiliar with - a bunch of descriptive comments can help you out.

Sure I could work out the code eventually, but a few comments which take seconds to write could save me a couple of hours working out how the Zooblargh function actually Zooblarghs.

My commenting style is based on what I'd like to see in other people's code.

I'd also argue that maintaining comments should be part of maintaining code. They should grow and adapt as the program does.

Joel Goodwin
Thursday, March 20, 2003

surely the classic is:

using namespace std; // so sue me

Scott Mayers wasn't it?

Nice
Thursday, March 20, 2003

My favourite was

* Hard coded so I can get home for Christmas
* Fix in New Year

Needless to say this comment and the code with the hard-coded value stayed untouched for years.

I think my second favourite was

* Note, this code should never be executed

And I did once write a comment myself which said

* Sorry this is a kludge

But I did eventually tidy up the code and remove the comment, although only after someone asked me what a kludge was.

David Burke
Thursday, March 20, 2003

Ive always found that the comments that are most useful are those that explain why code does what it does, and what else was tried.
Code that says *what* the code does is just embarrassing....like the idea of a comment that documents what parameters a function takes...I can *see* what parameters te parameter takes, and what it returns.  I like to understand why a copyfile function first clears the current graphport, or why a drawing function ends by writing to a file.
this type of code:
bool sendPrivateDataHome(char* someCharPointer, int y)
{
// function takes a char* and an int in that order
// and returns a boolean value

}


drives me mad....comments should assume that the next reader can understand code, but needs to know why things that are slightly different to what may be expected are done that way.

only wimps use comments....real programmers remember it all for ever
Thursday, March 20, 2003

Re FIXME
"Take the time to fix the problem instead of leaving half done work."
That's okay if everything else is in place and working that needs to be in place and working in order to fix it. Often however whatever it is you want to fix is actually not possible until someone else has fixed their mistakes. And if you are waiting for Microsoft to fix the MFC for example then you might as well just shoot yourself.


Thursday, March 20, 2003

I'm used to write a simple description of the part to do before coding. And then it's just 'fill the blanks'

Ros
Thursday, March 20, 2003

The worst comments appear to be in the "Learn VB" textbooks.

Here are two examples from Sams and Microsoft Press

Pr Ready = True  '  User pressed OK so return true

and

'  Open the PaymentHistory form and set its filter.

DoCnd.OpenForm "PaymentHistory", , , "SubscriberID= " & Forms!Subscribers!SubscriberID

The O'Reilly book on Access programming is a lilttle better in that it tends to use less comments and put the comments for the whole sub at the top so you get a quick overview, but still can produce beauties such as

'  Declare Static Boolean Variable
Static NotFirstTime As Boolean


My Sybex Access VBA manual does not comment any code at all, which if the above examples are anything to go by at least saves paper and ink, but some of you may be getting an inkling as to why so much of the VB code you see  is uncommented. Us amataeur VBA programmers aren't naturally brain dead; we've gone through a long process of acclimatization!

Stephen Jones
Thursday, March 20, 2003

I work on a medium sized (70K line) C++ project. We use literate programming to aid us - we automatically generate documentation from doxygen.

Our "house style" is that header files should be commented using doxygen markups in comments as completely as possible. The source (.cpp) files then only contain comments pertinant to the code (not Doxygen markups). Generally this means that within methods, each code block has a praece'd explanation (what it is doing), together with any elucidation of why or how it should be done.

The only additional markup we use is // NOTE: ... This is so we can grep the text for any outstanding issues easily.

For example:
/* Create a set of actions on receiving the measurement report (adds /deletes).
  Actions will then be added to the lists of pending adds or deletes. We won't start executing deletes until all the adds have been completed, because we want to avoid emptying the active set.
NOTE : Jim thinks the standard may have altered - check with the architects.
*/

It is very true that "good code documents itself", in that it is clear, well written, and easy to follow. However, not everyone who reads the code is a developer. On our project, we are amixture of simulation specialists (the main developers) and systems engineers (not C++ folks).

Putting more general comments in the code means that they can more easily follow the code if they need to look at it, which they do quite regularly. For example there may be some discussion on precisely how some feature should be implemented. They don't need to understand the detail of the sode, but they do need to follow the algorithms that are being used.

Hope this helps


 

The reason we use paece'd explanations

treefrog
Thursday, March 20, 2003

I work with one guy who comments just about every line of code he writes.  Every single line.  It is BEYOND annoying.  Oh, and he doesn't put any space between things to make it easier to read. 

Even things like try/catch blocks get the helpful comments "// TRY." and "// CATCH." every single time. 

Andy Frennick
Thursday, March 20, 2003

My favourite comment is probably:

# gerbal variables (eek)


What I usually do is write comments as a summary for each block of code.  That way someone else can get a good feel for what the code does without having to read it.  And more importantly, it means they can identify a particular area they're interested in without having to read the entire sodding file....

JP
Thursday, March 20, 2003


//Here be dragons ...

and

/*Magic*/

and

/*Deep Magic*/

regards,

Matt H.
Thursday, March 20, 2003

and of course

// left of witchcraft

treefrog
Thursday, March 20, 2003

first day of my first job....browsing through the code and see this

// Thou shall not use private variables

a little farther down way off page (around col 200) was a note he left to call his girlfriend, phone number and all :)


the author of this is no longer an employee.....

apw
Thursday, March 20, 2003

Comments are to answer and questions has or
should have. You can answer many questions
via good name selection and clear code, but
you can't answer a good portion of them that way.
Think to yourself on every line what questions
you would have about the code? Why are you
doing it this way? What would happen if you
did it a different way?

valraven
Thursday, March 20, 2003

About two years ago, I commented out a block of code while working on a consulting project.  I left the following comment along with the code.

//  They think they don't want this code, but they will!

About a year ago, I got an IM from a developer working on the project.  He had just uncommented that block of code and was laughing his head off.

It's nice to be right.

Then there was the English major I worked with back in college.  His comments were rather like short stories interspersed with code.  Stuff along the lines of

//  The golden dragon rises on wings of flame to greet the
// dawn, and now we proceed to find the next node in the
// tree

only much much better.  I could have read his comments for hours.

Bruce Perry
Thursday, March 20, 2003


I once stuck the entire "You're not my father" scene from The Empire Strikes back into some C code.

After I left, some folks found it.  It was pretty funny ....

Matt H.
Thursday, March 20, 2003

Like some others have posted, the "what" is in the code, but the "why" is not.  I document things like:

- design decisions
- thoughts and ideas on future changes (added features, refactorings...)
- things you should be aware of when calling/using the code (usage idioms, non-obvious implications of calling certain methods)
- why I made a certain change

If the code is complex enough I'll also put together a brief, high-level "how it works" comment.

-Thomas

Thomas
Thursday, March 20, 2003

I guy I used to work with was into his star teck and sci-fi. He used to make the most simple code unreadable by naming variables after characters and the like.

Made it almost impossible to know what was going on when you cant remember what intWarpFieldStrength of dblGoblinFactor is really counting.

One SQL proc he wrote returned 666 if it tried to do a divide by zero. "Why?", we asked.

"Becase thats the number of the beast."

hmm

Colin
Thursday, March 20, 2003

And please, do not put your name or initials in the code without your phone number :-)

Actually, this functionality is best left to PVCS,sccs,rcs, cvs or whatever code management system you should have.

Paul B
Thursday, March 20, 2003

I was responsible for a large amount of "legacy" code at one organization, and as new employees were hired some of the new arrivals took issue with my historical commenting style, and I laugh because it was similar to some of the ones given at the beginning of this discussion as "bad examples"

-I never comment what is obvious to any half-competent programmer: Comments that describe the basic constructs of programming are comment-masturbation: They're not for anyone else's good, but rather for someone to say "look, I comment good don't I!". >95% of "good" comments are complete and utter typarrhea.

-I _do_ comment things like "// TODO: This is a nasty hack" or "// TODO: This needs to be thoroughly evaluated for completeness". I laugh when I read people say "Well then fix it then!", as if programming were so straightforward and trivial, and timelines could be so grandly accommodating. As Joel said in one of his articles: This is anthropological GOLD that you should savour, not criticize, and any firm that thwarts comments of that sort is a firm with its head thoroughly planted in the sand. There was one case where a file transfer routine would abort if a particular set of characters came in, and I wrote in the code "// TODO : What happens if a file just happens to have this particular sequence of characters?". It came in handy when a particular chance file struct the abort paydirt several months later, and a big lightbulb appeared over the next programmer's head.

Jimmy Chonga
Thursday, March 20, 2003

/* Holy Bad coding style Batman! */

Personal favorite found in living code.

!
Thursday, March 20, 2003

while (something)
{
    ;;;;;    ;;;;
    ;    ;  ;    ;
    ;    ;  ;    ;
    ;    ;  ;    ;
    ;    ;  ;    ;
    ;;;;;    ;;;;
   
 
    ;    ;  ;;;;    ;;;;;  ;    ;    ;    ;    ;  ;;;;
    ;;  ;  ;    ;    ;    ;    ;    ;    ;;  ;  ;    ;
    ; ;  ;  ;    ;    ;    ;;;;;;    ;    ; ;  ;  ;
    ;  ; ;  ;    ;    ;    ;    ;    ;    ;  ; ;  ;  ;;;
    ;  ;;  ;    ;    ;    ;    ;    ;    ;  ;;  ;    ;
    ;    ;  ;;;;      ;    ;    ;    ;    ;    ;  ;;;;
}

Rob Daugherty
Thursday, March 20, 2003

Dang.  Life was better before proportional fonts.

Rob Daugherty
Thursday, March 20, 2003

/*
* Abandon all hope, ye who enter here
*/

S. Gwizdak
Thursday, March 20, 2003

(Sys V source):

/* you are not intended to understand this */

punter
Thursday, March 20, 2003

Paste Rob's Daugherty's comma message into Notepad

Stephen Jones
Friday, March 21, 2003

How not to do it, but still a funny read: http://mindprod.com/unmaindocumentation.html
-- Christian

Christian A. Riis
Friday, March 21, 2003

Have a look at  http://www.cloanto.com/t-shirts/ 
It doesn't seem they sell those shirts tough.

agnul
Friday, March 21, 2003

I've been working on-and-off for 3 years now on a project on which I am the main programmer.  I find my comments from 2 and 3 years before absolutely necessary since I've completely forgotten the points of the algorithms, so more than commenting for the "next" maintainer, I comment for myself, too!
One of the best things I include at the top of functions is a list of those that CALL it.  If I need to change the parameter list, when updating, it is very helpful and much quicker than going thru large flowcharts.  This also suggests which test cases to try.

Barry Sperling
Friday, March 21, 2003

Barry,

I find that commenting for my future self is very important too. Also, like you I find it helpful to list some sample functions that call a function. I don't keep it comprehensive nor use it as a directory (that's what Batch Search is for), but as a quick reference to the context in which the function is used.

Ed the Millwright
Friday, March 21, 2003

*cough* Or Barry you could get a debugger than shows you the cross reference information for various symbols (such as procedures, variables, classes, etc) so that you don't have to use grep, flow charts, or possibly-out-of-date comments.

But then, I'm biased. :)

Steven C.
Friday, March 21, 2003

/* This is VERY hacky... MUST FIX before alpha! */

Found in code written 10-years ago which is still part of the core libraries for one of today's most popular programs.  I better not say which company I work for. :)

Colonel Angus
Friday, March 21, 2003

All of their comments are belong to someone else http://www.codeproject.com/scrapbook/funny_comments.asp


Monday, March 24, 2003


>Static NotFirstTime As Boolean

Ugh. Breaks rule number one in my programming book;
Thou shalt not negate boolean variable names.

if not NotFirstTime then ..... // Total uglyness.

Note to self: Dont buy that O'Riely book.

:-)

Patrik
Monday, March 31, 2003

hi all!
I code more in web environment, that's why I got some experience with JS commentars.
As you might know it is very helpful to check the version of the clients browser when assuming to use some JS code.
What I found as a commen:


if(version>5)
{
...
  ...
}
else{
//alert('Our remarkable software is not been thought for Your stone age browser! ');
}


                cheers
                            dian

Dian Baltadzhiev
Monday, February 16, 2004

*  Recent Topics

*  Fog Creek Home