Building Code to Last

October 12th, 2006

I’ve just spent an hour re-factoring some of my code. I also put some comments in, because there weren’t any when I started. I also wrote some unit tests I should have done before writing the code, and actually ended up fixing a bug that would happen in rare cases. I also made it smaller, faster and less of a CPU hog. I increased the readability and fixed a couple of indenting issues.

What surprises me is that I didn’t do any of this when I wrote the code in the first place.

I think part of the problem is that when you have a deadline, you just care about getting a solution together that works, and you want it ASAP. You don’t care about elegance when the bosses are crying for a customer sign-off at the end of the week. As a result, you take shortcuts, jump around and deploy code that “will kinda work” and just hope it never fails. Or at least, hope it never fails whilst you still work there.

Strangely, some of the best code I’ve ever seen out there is open source, which feels counter-intuitive - it’s a bunch of people doing hobby code, not something they are being paid to produce. I think it’s because there is no deadline with open source that makes it better. It has been said that programmers work on open source projects in the evening because it’s relaxing. Without the deadlines, pressures and insistence things are done a certain way, developers can revel in the intellectual nature of development. As a result, they take the time to unit test, to comment, to document to re-factor properly.

One of the interesting conversations developers could have with customers and their management is to ask “Which is more important? Code that kind of works right now, or code that is built to last?” and I think the conclusions would shock us. Most customers don’t care that you got a big block of code reduced down to a really nice recursive loop. Most bosses aren’t bothered about comments in code, because they don’t know the real price of not having them.

This exercise tonight has convinced me I need to change my working practices, and I need to stop trying to undercut on prices - I need to price as a job, raise the time estimates to remove the deadlines and start promising to produce code that is built to last. What I’m worried about is that this isn’t a very good sales strapline: we’re more expensive and take longer because we do stuff you don’t care about.

Even so, I think it’s worth doing. Quality code makes me happier than quickly developed code.