Tales of the Rampant Coyote
Adventures in Indie Gaming!


(  RSS Feed! | Games! | Forums! )

Friday, November 17, 2006
 
Programming Tip: Comment First
Here's a little programming tip that helps me write better code... when I remember to do it. I don't have a really good name for it. I'll just call it the "Comment First" technique for now. I find this trick helps me focus on programming tasks better, helps me stay on target when I'm interrupted, and provides me with nicely commented code.

The technique is simple: When I create a function / method / whatever, I create a stub, and I write the details of the function implementation in plain English inside the stub. (I suppose if English isn't your primary language, another language of choice would suffice. I dunno, I haven't tried.) I format the description as comments, and I try to break them into steps with whitespace between them (blame my learning procedural programming back in the early 80's).

This is sort of like writing pseudocode, which is one of those almost-perfectly-useless things they taught me in college. I never really understood the purpose of using pseudocode outside the language-agnostic classroom. Unlike pseudocode, what I'm talking about is not writing anything that resembles machine-readable instructions. This is purely human-oriented instructions to yourself on how you are implementing the function.

For example, here's a simple function I was working on tonight. This is nothing more exciting than implementing queue behavior in TorqueScript:

function WBQueue::Pop(%this)
{
// Is the list empty? If so, quit.

// Grab the top element in the queue.

// Does the first element have a successor? If so, point the Qeue to this second element.
// Otherwise, set the Queue it to NULL (0).

// Return the original top element

}


The first benefit I gain from doing it this way is that it forces me to analyze the problem from a higher level before I start coding. For example, this code (with some expansion to functionality) was being used in tonight's project to keep track of a scrolling, ordered selection of graphics objects. I was going to implement it with an array. As I thought through it, I realized that it was simple queue behavior. As soon as I think queues, I think "linked list." I'd never implemented a linked list in TorqueScript before, but as I thought about I imagined it would be very easy. And much cleaner than the array approach.

Once the instructions are written out this way, writing the code itself is almost trivial. At this point, I can put my brain on auto-pilot and code away. A side benefit is that if I'm interrupted, it's easier to eyeball what I was doing when I left off, and to pick it back up again.

Another advantage is that, when I am done, those little instructions to myself remain as comments for my code. When I come back to it six months and try to figure out what the heck I was thinking when I wrote the code, I'll take a look at the comments and realize I wasn't such an idiot after all. That does wonders for my self-esteem.

So there you go. Nothing rocket-science-y about it, but I thought I'd offer it here as a suggestion to any other code monkeys reading this.


(Vaguely) related items of questionable value
* Biting the Silver Bullet
* The Joy of Debugging
* Fitting Game Development Into a Full-Time Schedule
* Fighting Procrastination: The Local Maxima Problem

Labels: , ,



Did you enjoy this post? Feel free to share it: del.icio.us | Digg it | Furl | reddit | Yahoo MyWeb

Comments:
Yes! I do this too, and I have found it to be so helpful in keeping track of what I'm trying to do. I first started trying this after reading about Knuth's Literate Programming idea.
 
I do this too, I'm not even a 'developer' I'm a QA guy.

It allows me to concentrate on specific portions of my tasks, breaks down a complex scenario and allows me to think through the logic before coding.

(with the added benefit that I can easily tell what I was thinking when I wrote the code)

Brian H.
 
If you write the tests first, I think you gain the advantages of thinking it through, as well as the important tests to verify that it does work as promised.

Of course, this isn't an either-or choice; if someone wrote comments and tests before their code, I bet they'd reap many benefits.
 
Yep! I've done test-driven development before, too, and while I was pleased with the results, it wasn't quite so overwhelmingly positive that I've made it part of my standard procedure.

Yet.

A little part of me still screams "Overkill." More work than it saves, though I don't know that for sure. However, it's still one of the first things I reach for in my bag of tricks when I have to deal with code that is critical, nasty, or hard to maintain / debug. Like network code, collision detection, etc. In those cases, it's clearly a win.

Thanks for bringing it up, Joseph!
 
I usually do this as well (except when I get lazy), as I been burned too many times going back to my old code and trying to figure out what the heck it does now. I also place a short comment before the method/function which describes what the whole method/function does.
 
I find that I do this as well, although I do it both before and after I program a particular method. I'm notoriously bad at interpreting what I wrote a long time ago...not only the overall purpose, but the reason for each individual step.

It's overkill...only until you hit that speedbump and realize how grateful you are that you put those damn comments in there.
 
Yeah - I'm a big fan of well-commented code.

I've been the rounds with folks about "self-documenting code." And I agree with code being as human-readable as possible. But what I've found is that code can tell you the what's and how's of what you are doing, but not the why.

So it's all well and good to look at it and say, "Oh, I'm now I'm calculating the vector between these two objects." But it doesn't answer the question of WHY you are doing it here instead of right before that vector is being used... You might have had a perfectly good reason, which you otherwise might not discover until you change it, break it, remember why you did it that way, and change it back...
 
while we're on code documentation I thought I'd throw out thies oldie but goodie link :)

The Commentator

http://www.cenqua.com/commentator/

Brian H.
 
Okay, now my question is... how come there is Japanese (?) characters for my adsense ads in this thing? I wonder what they are selling...
 
I do that too, but tend to keep the notes at a higher level. So instead of describing the logic, I'll write "foo is implemented as a stack", or "foo acts like a hash and an indexed array at the same time; elements added without a key are not added to the hash. The hash contains pointers into the indexed array."

I also put in descriptions next to each "return" describing the output, and why that specific return is being called, if there's more than one. That disambiguates the intent of the logic.
 
Anonymous:

Using higher-level comments is certainly another godd approach.

I tend to prefer the mid-level comments myself possibly because I'm prone to brain-farts (usually caused by interruptions, either external or self-inflicted) in the middle of developing a feature. Having the comments arranged in step-by-step instructions or as kind of "notes to self" helps me reduce the ugly spool-up times involved in task-switching.

The return value comments are golden. That SHOULD be common sense, but it's not... at least not in the "real world." Even if you've done a really good job of using descriptive constant names, the 15 seconds you take describing the why's pays for itself the first time you go back to maintain the code after it's memory has gone stale.
 
This technique is descrbed by Steve McConnell in _Code Complete_
 
This technique is discussed in _Code Complete_ by Steve McConnell.
 
Is it? I've read (much of) Code Complete, but it's been a long time. Maybe I picked it up from there? Or more likely picked it up from someone else who picked it up from there.

Well, if Steve McConnell agrees, then it must be good advice... ;)
 
You say this isn't pseudo-code, I say it is. It's just pseudo-code at a level of abstraction that you feel the benefit of using it. Psuedo-code at a more detailed level inevitably becomes "just another programming language", even if it's one that you can translate into the target language easily.

I do this occasionaly, as I feel it suitable. Something I do more often, finding it more useful, is to write a block of comments just before the function describing it's arguments, results and any side effects on a conceptual level rather than a procedural one.

For example a method/function might have a comment stating "sorts the argument list of 'whatevers' by 'sommat' and returns an ordered copy".

Once I've got these comments I then fill in the bodies of the methods. Why do I do this? It helps me go through the interface to my code and helps me ensure I've thought it through, and provides some documentation to the maintainer and/or user (indeed if something like javadoc is available I tend to use that for just this purpose).

The pseudo-code comment and interface-checking comment methods both have the benefit of helping the user think things through - of course no one will use all of the time, and if you're familiar with the domain then you might not bother at all. Your mileage will undobutedly vary.
 
This is fine, but do you keep your comments acurate as you fix bugs and refactor? I've found that well commented code with a little age can be very misleading. The code works correctly but only after several rounds of bug fixes and the developers forgot to carefully review the comments and keep them accurate.

Good suggestion, but I would say you should expand it to fix the comments before the code when making any changes as well.
 
I don't know about whether or not I'd call that pseudocode. Pseudocode was always presented to me as something a bit lower-level than what I do. But I guess that's a semantic issue. The important part to me is that it needs to express how I'm approaching the problem - my strategy - something that code (and, in my opinion, pseudocode) itself can only express through extrapolation.

Comment Maintenance: Yep, when I was programming in an eXtreme Programming shop, that was a big deal, and while I can't say the habit stuck *perfectly*, I do try to keep my comments up to date when I can.

The challenge is working with others who don't follow this same practice (and again, I'm not super-dilligent about it either... but it helps). Trying to decipher what they were ATTEMPTING to do with a dense block of code and make sure you don't break something by eliminating a side-effect they were relying on can be a challenge. Rather than editing their comments directly, I sometimes just add my own... sort of having a running conversation in comments.

I think they rarely actually see or respond to those comments later, but I hope anyone coming in after us might be able to see what's going on.
 
Post a Comment

Links to this post:

Create a Link



<< Home

Powered by Blogger