Fog Creek Software
Discussion Board

How should I comment code?

Yes, i'm confessing, i'm absolutely horrible at commenting my code.  I guess I'm just so used to my code, that it makes perfect sense.  I don't think my code is ugly, but looking through some of my recent projects, the only comments are simple small little things written to myself.  When I do right comments, they look absolutly useless, mostly things like "validate the user by checking the session".  How can I learn to comment well?

Vincent Marquez
Friday, May 2, 2003

I think the most important thing is to document your assumptions and contracts. A lot of things (say get/set methods) have largely obvious contracts. However, if it doesn't, for instance I have some object/relational stuff that uses abstract classes that delegate parts to subclasses, to facilitate code sharing. I document the contract between super- and sub-classes thoroughly, although a lot of other stuff isn't documented at all.

Mike Swieton
Friday, May 2, 2003

I suggest writing your code comments prior to coding and adjusting them after writing each module / function / class / etc.  In that way you'll make yourself think through your code and at the very least provide a sort of running commentary.

Often times what gets commented is what each line does, which tends to be rather obvious.  What I need to know to understand your code is why are you doing this, why does this module exist, and what are its weaknesses / strengths / assumptions.  Its the assumptions which are key - those maintaining your code should know if your function which returns ASCII values for characters only works for capital letters which are vowels.

Friday, May 2, 2003

Document the why, not the how.  When I find myself writing things like

# loop through all of the users and mark for later
foreach $user ( @users ) {

I stop myself, and erase the comment.  Then think of why I'm doing that, and try to write that down.

I've tried to start writing a more high-level document to go along with the source as well, that is more of a running commentary about different parts of the system, why they're done that way, and quirks to watch out for.  Then the lower level comments don't have to have paragraphs of explaination.  I can just refer to concepts in the other documentation.

Andrew Hurst
Friday, May 2, 2003

This may not be very efficient, but it works for me.

I write my code with a minimum of comments (which is still probably more than most) because at the time I often don't appreciate *what* needs to be explained. I then come back to that code later to write the comments with a fresh perspective. 

This has two benefits:

1)  I can better understand what needs to be explained.

2)  It helps me to discover flaws, a sort of self code review.

But as I said, it's probably not that efficient because it means spending time relearning the code, but IMO it results in better comments and better code.

another programmer
Friday, May 2, 2003

I also recommend "documenting the why, not the how".  If a portion of the code is tricky, took a long time to write or debug, or is just not intuitively obvious, put down a comment explaining the subtlties of the code.

Another practice I use is to organize my code in a large function into logical blocks of 5-15 lines, and put a comment at the top summarizing what is going on.  This helps someone who is new to the code navigate exactly what is going on and where.

Friday, May 2, 2003

I like write my code using "paragraphs", blocks of 5-10 lines of code that have a common goal. I can comment each code paragraph's intent (the "why, not the "how").

If you have TOO many comments, then you should consider simplifing your code. You can either use more descriptive variable names or, even better, refactor the complex code into smaller functions with clear, descriptive names.

Friday, May 2, 2003

You should spend some dedicated time pieceing through other people's code and figuring out how easy it is to grasp and what they did right or wrong with making it visible to you.

Flamebait Sr.
Friday, May 2, 2003

I usually use /*  */ style comments.

Friday, May 2, 2003

I like a paragraph, in plain English, above the class or function explaining what it does and why it does it.  For me, this eliminate the need for 99% of in-code comments.  The remaining 1% is for portions of the code that are complex or generally less transparent.

Friday, May 2, 2003

A short answer to most (but not all) commenting questions:

"Refactor the code properly and you won't need comments."

See also:

Also think about comments in terms of code maintenece: if YOU are writing it, but it is so complex that YOU need a comment to keep it straight, then how will any other poor sap every understand what you were writing?  :)

My general rule is to comment only what I cannot express in the language itself.  If a five-line block of code all works together to do one thing, then I refactor it and give it a meaningful method name, rather than put a comment on top of it.

John Lindsey
Friday, May 2, 2003

nobody will read your code anyway. the next person will come in and say I don't want to change anything.

Pepe Le Pew
Friday, May 2, 2003

Yeah, I often think that really terse C-style method naming creates an artificial need for commenting.  It pisses me off when I see people using it in other languages to make creat().

Friday, May 2, 2003

What I ask myself when I write code is, will I understand why I wrote what I did if I do not look at the code again for a week, month or year from now.
All too often I come back to my own code and can not discern why I needed to write what I did.  I know it made sense when I was in the zone, but if you are not in the zone it can be totally baffling especially if there is a lot of interaction with other classes.
I try to be particularly careful with functions that return boolean values. Again I often come back to a boolean function and find myself asking, what does returning true really mean.

Saturday, May 3, 2003

John Lindsey wrote: "My general rule is to comment only what I cannot express in the language itself.  If a five-line block of code all works together to do one thing, then I refactor it and give it a meaningful method name, rather than put a comment on top of it. "

I have to disagree with that. You write code in a language that language compilers understand best. These languages (although much clearer than say assembly ..) are still a far match for English. In any case - at most they explain the "how" - not the "why" which is IMHO the quintessential piece of information that is needed to understand and maintain a code base.

I'm sometimes disappointed to see that extreme programming folks (martin fowler being one of them) tend to wrap good ideas (like refactoring) with completely nonsense ones (like the one I'm writing about, careless design attitude and the like) which leads people to adopt the whole thing as the One Big Truth.

Liron Levy
Saturday, May 3, 2003

A quick fix to my last reply: I actually ment to commenet the first paragraph in john's reply:

"Refactor the code properly and you won't need comments."

It seems that john is doing the right thing after all ... my
apologies :-)

Liron Levy
Saturday, May 3, 2003

The hidden error in the statement 'only comment what you can't express in the language' is that that implies a complete understanding of wot you wrote, or that if you understand it will you in the future or will anyone else.

For instance I might really have meant to write


but that doesn't mean I really understood what the effect would be, nor could I assume that others would in the future.

A comment would certainly be needed on such an obfuscation (apart from a sharp metal object up the rear of the author).

Simon Lucy
Saturday, May 3, 2003

Big headers for every function, commenting the parameter types and what they are.  Something like this:

* Function: foo
* Author:
* Paramerers:
* int x  this is the 'x' parameter, it is of type int
* int y  this is the 'y' parameter, it is of type int
* Returns
* z, the foo trasform of (x,y)
* Comments:
*  This function performs the foo transform over
* parameters x and y
* Known Bugs: None
* Written: 0/00/0000
int foo( int x, int y )

Big comments are like big hair: they make you sexy like Farrah Fawcett, Dolly Parton, and those religious TV personalities.  You might even become "architect" someday.

Nat Ersoz
Saturday, May 3, 2003

Just comment from a “how to use perspective” instead of a “how it works” perspective.

See also:

Ana Vallejos
Saturday, May 3, 2003

OK, sorry...  don't do that.

Make some basic assumptions:
1. The person reading is skilled in the language.
2. The person reading is skilled in the subject matter.
3. If you're coding to a specification, it is a good idea to reference it when applicable.  That's what you're implementing and lots of documentation is there.
4. If you don't have a specification, start writing one.  Keep it light wieght, text only if you like (note, IETF RFC's are all text only - if its good enough for Al Gore, itsgood enough for me).  Keep writing it as you go.  IMO, its prefereable to keep specification like information in a spec, not code.

To borrow from an example:


I wouldn't document the syntax (obfuscated as it might be).  I know that the compiler knows how to read properly - it doesn't care.

However, someone might like to know that:

"We need the next table element's array byte since it was stored during the previous loop as we filled the table backwards and now require its spunge value in order to continue parsing our current table.  See table syntax and spunge spec XXXX, section 4.2.  This loop is optimized for tables written backwards, as delivered by vendor xyzzy."


Nat Ersoz
Saturday, May 3, 2003

Nat, I do write comments like that for my classes I write that will be used by others. [wohoo i'm gonna be an architect ;-) ]

Thats not too tough, but what I have trouble with is deciding how much to comment the "mundane" code.  Occasionally I find myself looking at really simple uncommented code a while ago, wonder why I did something, and then after 10 minutes of frustration I realize I did something a certain way because of a "language" quirk. 

Overall, some really good suggestions comming in. Thanks guys.

Vincent Marquez
Saturday, May 3, 2003

Saturday, May 3, 2003

"Make some basic assumptions:
1. The person reading is skilled in the language.
2. The person reading is skilled in the subject matter."

Unfortunately, one or both of those assumptions often turn out to be false, because companies like to give maintenance programming tasks to those with less experience or those who are new to the company.

T. Norman
Saturday, May 3, 2003

I'm a non-programmer intruding on this thread, but I though I'd make some comments.

I always find it helpful when there's a big chunk at the top of any large section of code that says what it does... Saves me time figuring it out.

Then in the small sections I like comments that explain what the little section does. Saves me from having to trace variables and functions back to their source.

Then again, I don't really read code, so all variable names throw me off, and the nice plain english explanation at the top really helps me figure out what's going on.

When I'm writing anything for myself, I just tend to comment the tops of small code chunks with what I'm thinking at the time.

// changes the color of the font if such and such
// and it might make sense to blah blah

Why? So I can scan the page quickly and find that chunk. Maybe it's because I don't think like a programmer, but I find it helps break up the page as it's scrolling by.
Sunday, May 4, 2003

McConnell has some good things to say about comments in "Code Complete". Check out Chapter 19, which is all about comments, and the PDL parts of Chapter 4.

Bill Tomlinson
Monday, May 5, 2003

*  Recent Topics

*  Fog Creek Home