Latest News
spacer View All spacer
 
November 22, 2009
 
Video Game Watchdog National Institute On Media And The Family Shutting Down [11]
 
Modern Warfare 2 Infinity Ward's 'Most Successful PC Version' Yet [13]
 
New Tech, Design Details Of Project Natal To Emerge At Gamefest In February
spacer
Latest Features
spacer View All spacer
 
November 22, 2009
 
arrow Upping The Craft: Susan O'Connor On Games Writing [6]
 
arrow Small Developers: Minimizing Risks in Large Productions - Part II [7]
 
arrow iPhone Piracy: The Inside Story [49]
spacer
Latest Jobs
spacer View All     Post a Job     RSS spacer
 
November 22, 2009
 
Trion Redwood City
Sr. Environment Artist
 
Trion Redwood City
Sr. Evnironment Modeler
 
Sucker Punch Productions
3D Environment Artist
 
Sucker Punch Productions
Network Programmer
 
Sucker Punch Productions
Texture Artist
 
Sucker Punch Productions
Character Artist
 
Crystal Dynamics
Sr. Level Designer
 
Monolith Productions
Sr. Software Engineer, Engine - Monolith Productions - #113767
spacer
Blogs

  Make Your Bed, Eat Your Veggies, and Comment Your Code
by Neil Gower on 07/17/09 05:35:00 am   Expert Blogs   Featured Blogs
12 comments
Share RSS
 
 
  Posted 07/17/09 05:35:00 am
 

Every programmer knows they're supposed to document their code. Just like keeping your apartment clean though, documentation often gets put off until "later". Also like cleaning, it's easier to do documentation as you go, rather than in a big push at the end of the dev cycle. A pragmatic commenting style can go a long way to making this a reality. Below are some tips to make commenting less of a chore.

Agree on a format

To me, order and consistency make code look right. If you work this way too, it's a good idea to settle on a common format for your comments. A couple possibilities for functions:

//-----------------------------------------------------------------
/// YOUR COMMENTS HERE //-----------------------------------------------------------------

/**
 * ... OR YOUR COMMENTS HERE INSTEAD
 */

Both of these are doxygen compatible. The first has the nice property of indicating the maximum line length, which is good for consistency. Typing codeIt's a bit of a hassle to type, so you'll probably want to create a macro for it in your editor of choice.

The second format is easier to type, and less fussy about line lengths (good if you are also less fussy about such things). It's not quite as visually impactful, but good use of whitespace can fix that. Pick something that works for you, and stick to it.

Keep it simple

It's easy to get carried away when trying to come up with a coding standard. The trouble with getting too elaborate is if the standard creates too much work, the temptation to ignore it will be overwhelming. Short comments also minimize wasted effort when you change or delete a function.

My suggestion is that any standard should accept this as a valid comment:

/**
 * Sorts the objects in place in front-to-back order.
 */
void sortFrontToBack( SomeContainerClass& toSort )

The point here is that while you could add more detail, you shouldn't have to. A one-liner is much better than nothing at all.

Don't redundantly repeat yourself over and over again

You don't need to restate things that are clearly stated by the code. It's fair to assume that the reader of your code understands the programming language you're working in. Let's say you're documenting a function like this:

int getOrgreCount( Zone& queryZone )

The name of the function is obvious, don't put it in the comment. Explaining that the queryZone parameter is a reference to a Zone object, also redundant. Returns an int, redundant. Really, all you need to say here is something like:

/**
 * Returns the number of ogres in the queryZone, or -1 on error.
 */

On the other hand, if you're working in a loosey goosey language like Python, commenting on the expected type is a very handy thing to include in the docs.

Develop a mental checklist

Sometimes you stare at an undocumented function and think everything about it is so obvious that anything you write would be pedantic and useless. This happens a lot when the code is designed well to start with and uses informative names. To get past writer's block in these situations, develop a mental checklist of things that might be worth pointing out, such as:

  • Parameter descriptions. Do any of the parameters need explanation? Are only certain values allowed or disallowed?
  • Error conditions. What happens when something goes wrong? Does the function return error codes, raise exceptions, etc.? Does it always leave the program in a valid state?
  • Limitations. Are there cases that the current implementation doesn't handle?
  • Performance guidelines. Are there cases where the function is really slow? Are there things the caller can do to make it fast?
By running though a list like this, you'll rarely be at a loss for words.

These tips will hopefully encourage you to tackle documentation proactively. Documenting code is part of being an organized professional, but it doesn't have to be a big chore. Most of the time, we're not building public APIs that need exhaustive documentation. Just leave your teammates and future-you some useful notes about what's going on in the code, and you'll soon be reaping the benefits of documented code.

 
 
Comments

Robert Allen
profile image
My code is usually commented because I code IN comments. I write a comment down telling me what I'm about to code, then I code it. Coding after you're written the code is a recipe for poor commenting, IMHO.

Roger Hågensen
profile image
Interesting idea Robert, I usually do that in my head, never thought of writing it as a comment first though as my code literally is the comment (I easily read the code itself). Then again, my prefered coding language is PureBasic so...

What I hate about C and it's derivatives and cousins is the damn brackes, not the brackets themselves but the way people illogically place them.

Each time I see:
if () {
//something
}

I'm itching to change that to:
if ()
{
//something
}


Which makes so much more sense, the opening and closing bracket is now on the same level.
Many code highlighters will highlight the opening and closing bracket and having them on the same level helps see that quicker.
It also makes copying, deleting or inserting easier if the brackets are on the same level.

The other nitpick of mine is all the use of assert, as if that is a magic "make it work" trick, people forget it's just one of many debug tools and wonder why things fail when they release the program, or worse, the release the program with assert debugging still enabled, ugh...

Nice article Neil, although it could have been longer, re-iterating good coding practices tips like this is necessary as people (myself included) forget these from time to time.
I'm hoping for a follow up article in the future, maybe a mini series of articles on this topic even?

JJ Lehmann
profile image
Roger Hågensen:

"What I hate about C and it's derivatives and cousins is the damn brackes, not the brackets themselves but the way people illogically place them.

Each time I see:
if () {
//something
}

I'm itching to change that to:
if ()
{
//something
}


Which makes so much more sense, the opening and closing bracket is now on the same level.
Many code highlighters will highlight the opening and closing bracket and having them on the same level helps see that quicker.
It also makes copying, deleting or inserting easier if the brackets are on the same level."

I agree with you about that. It's much more readable the second way.
The reason people place brackets the first way is because they feel that brackets are statements by themselves, much like Begin and End in VB. If you think in that way, using the second layout style looks like this:

----------
-----
--------------------
--------------------
--------------------
-----

And the first is more like this:

-----
--------------------
--------------------
--------------------
-----

In terms of logical flow of the code, yes, the first style probably is more coherent, but all of that seems a little silly to me - sacrificing so much of the readability of the code just for the sake of a small gain in flow logic. And that gain doesn't really work to well in bracket-using languages, because brackets don't in the least resemble a statement, unlike Begin and End in VB. It just looks like a code block delimiting character.

Ian Morrison
profile image
I tend to code similarily to Robert... I'll insert "//TODO:" lines willy nilly into my code. For documenting files and members, however, I'm guilty of very informal commenting... I'll put something in describing what it does, but it'll usually be a // comment above or on the same line as the declaration with minimal information. Still, it's better than no comments at all... I've learned that the hard way after digging through my old code and wondering what the hell I was thinking! :P

Matthew Severin
profile image
Great article Neil.

Richard Marzo
profile image
Second that to Robert and Ian. It's like putting pieces of a design doc within the code, only you know instantly whether it's relevant and up to date.

Also, for the mental checklist, maybe include function call chains, of the kind that occurs in certain complex coding situations. Something like // Calls A, B, C and is called by D, E, F. Maybe that would get too cumbersome, but it would make code easier to parse for first-time readers, or novice coders (e.g. me).

Cool article, and I am glad to see another fan of Emacs. One question Neil, do you edit in the console or from X? I really enjoy the mouse support of Xemacs, and am maybe looking into using the embedded support for vi..dont really "know" vi yet, but I hear good things about it.

/* This comment was written by me and hopefully read by you */

Richard Marzo
profile image
On second thought, maybe "Calls A, B, C" would fall under redundancy, unless the call is stuck inside several lines of for loops and if statements. But "called by D, E, F" would still be helpful, since you can almost never tell from a stand-alone function which other functions may be dependent upon it.

Robert Allen
profile image
As I get older and realize I'm not the superhuman code monkey we all think we are, I now routinely add opening and closing brackets as mentioned above:

if ()
{
}

...before I even fill out the test code in the control structure. I've done that since the day I spent an hour of time trying to figure out why this kind of code wasn't working as I expected:

for (i=0 ; i < N; i++)
A += B;
C += A;

printf("doing stuff....\n);


// Do you see the bug above? :)

Robert Allen
profile image
Bah! Stupid boards removed my indentation. The bug was that both lines beneath the for() loop were indented to be in the loop, but since there were no braces, only the first line would be executed in the loop. You can stare and stare and stare at that bug and not see it.

Robert Allen
profile image
"using the embedded support for vi"

I'm a HUGE vi (that's pronounced "vee eye") fan having used it since college. Many of the commands are mnemonic which makes it easier to learn (anthing with 'd' or 'D' has to do with delete, 's' for substitute, 'c' or 'C' for change, etc.) But it's also fast. With liberal use of block deletes and then 'puts' you can move huge blocks of code around very quickly with practice. And there's no regular use of triple key combos unlike in emacs. The one thing that people find annoying about it if they already know most any other editor is, vi has two modes, insert and command mode. You're in one or the other and stay there for longer periods of time than in emacs, where by default you are in insert mode. If you spend more time entering code than thinking about it (i.e. reading /looking before typing) then you'll probably like emacs more. I'm not talking about coders vs code readers, I'm talking about two different styles of coding.

Andy Keeble
profile image
The problem I tend to see more is useless commenting taking up space making the code harder to read.

Comments before functions are the worst. I see the same stupid things cropping up. I personally think it's the fault of macros because it's so easy to get the information and have it make a comment for you that people just can't help themselves.

// Function name - Yeah, we already know that
// Purpose - useful and the one to keep, but it's usually the function name with spaces in it or words turned around
// Parameters - you should have named them well enough not to need extra info
// Returns - this is useful, but very often mentioned as the purpose of the function
// Extra info - got plenty already thanks

The information that's really needed in my opinion is the purpose, name of the author and when they made it so I have an idea if the author will still remember what it all does.

I also see a lot of adding comments to every other line of code, completely bloating things and making it harder to read. A lot of people have the practice of pseudo-coding with comments first and then using them as comments ..because you're meant to comment a lot, aren't you?

Often you'll make changes to the code but not change the comments too (very often happens with function commenting). That only adds to the confusion.

A good coding style should eliminate most commenting. If you're doing more than just giving an broad overview of what a section of code does, or noting that you're making a change to code that isn't originally yours, you're doing it wrong.

Neil Gower
profile image
Thanks for all the great feedback. I'm not going to touch the brace placement issue, except to say that both styles have their merits. :-)

@Roger: Future posts about coding practices are on the way. Maybe something about good uses of assert()...

@Richard: Noting important callers of a function is a good addition to the mental checklist, thanks! Re: Emacs, I usually use it with a graphical desktop, which could be X, or Windows, or OS X, depending what I'm working on. It's nice having one editor that works everywhere.

@Andy: Agreed, code can definitely have too many comments. If you catch yourself writing a lot of comments, it's worth stopping to think about whether your time might be better spent fixing the code
to be easier to understand on its own.


none
 
Comment:
 


Submit Comment