Wednesday, August 03, 2005

When To Write Comments

There's been a discussion over in Nerdistan about a recent Particletree article: Successful Strategies For Commenting Your Code and I thought I'd stick my two penn'orth in...

The usual way that people approach code and commenting is to dive in, code away feverishly through several iterations until they've got something that seems to work, THEN go back through it and add comments - if they have the time...

One trick I picked up early on in my development career - way back when I was coding massive invoicing systems on WYSE32 green screen terminals in 8-bit COBOL - that radically changed the way I approach the coding process is this:

Write your comments FIRST.

Yes - first. That's BEFORE you write any code. It's a very handy way of planning out your structure, algorithms, and data flow on complex chunks of code before anything is set in stone.

Otherwise, if you dive right in there and start coding away, you often realise halfway through that your first approach is not going to work, and you have to go back and change THIS structure, change THOSE parameters, add THIS call, take THIS chunk out into a separate function, etc etc...

I'm convinced that the vast majority of bugs in code are not due to lack of syntax knowledge, or even typos, but actually down to insufficient planning - not thinking the code through well enough before starting. Of course, this happens for many reasons - usually down to time constraints and/or scope creep - but the end result is the same.

Try writing your comments first - you should be able to walk through your process, follow the data, and catch most of the most common gotchas before you even write a single line of code. If you can't, then you haven't written your comments in enough detail.... Of course, you're always going to have to do the occasional rushed hack job, but I've found this approach tends to actually save me time in the long run.

Give it a go - <mrs doyle>ah go on.... aaAAAhhhh go ON, go On, go on go on go on....!</mrs doyle>

No comments: