Sunday 24 August 2008

Depth First Coding and Spirograph

Various analogies come to mind when I'm coding. Recently, the terms "Depth First Coding" and "Spirograph" have come to mind.

I'll explain.

When writing software, there's so much that needs to be done. But of all the items on the todo list, we coders prefer to work on new features than the other things like fixing bugs, dealing with security issues, general code "housekeeping" and basically doing what we know we ought to, but never quite finding the motivation for it. I know I certainly want to get to a stage where I can see the whole process of using my software from start to finish.

I think it's good practice to get a proof of concept up and running as soon as possible. As well as making sure you're not wasting your time with a project, you can get feedback right from the start, you can adjust your plan based on what you see, and let's face it - it's more fun - it can keep you motivated through the more mundane tasks.

To me, this feels like depth first programming - get the skeleton of the app complete, from top to bottom, then go back later and fill in the breadth - the bugfixes, the tidying up, the refactoring - the meat.

A breadth first approach would be to get all of the minutiae sorted - making sure each function was written as efficiently as possible, making sure the variable and function names were as descriptive as possible, commenting anything that wasn't clear, and basically trying to make each component as near to perfect as possible.

My problem with this approach is summed up in the phrase "Premature Optimization." Here we are going for perfect first time round, but at a cost. Then, if it turns out that the routine that we just spent the last day working on is no longer needed, then that's a day that's been wasted.

The way that a program grows, almost organically, reminds me of Spirograph. After the first iteration, a very basic, bare bones implementation is produced. After several more iterations a pattern starts to appear. After hundreds of iterations, the final picture is revealed. The pen traces a path around the spirograph, never lingering in one area for long.

This is how I see code growing organically. On top of the initial foundation, the coder grows the program piece by piece, often moving from one area to another. By jumping around the project, the coder doesn't get bored with the area they are working on.

But it's also worth noting that no matter how many times you go around a spirograph, and no matter how many different places you choose to start from, the pen doesn't touch every part of the paper - there are always some holes.

I wonder how the holes fit into my analogy...

No comments: