Thursday, 19 February 2009

The Importance of Clarity

I recently came across an interesting blog: Joel On Software. One post from way back in 2000 discusses the age-old dilemma of when to rewrite code, and has this to say:

The reason that they think the old code is a mess is because of a cardinal, fundamental law of programming:

It’s harder to read code than to write it.

This is so true, despite the fact that, all programming situations, we spend far more time reading code than we do writing it. It doesn't matter whether you are writing a totally new, greenfield program, or simply trying to fix a bug in an old one. You can't work out how the change or extend a program until you understand what it's already doing.

This is so obvious that it's hardly worth stating. It has a corollary which is not quite so obvious, however:

A programmer's most important task is to write code that's easy to read.


You might argue that it's more important to write code that works, but I disagree. The reason is that if you write code that's easy to read, you'll be able to fix the bugs, and so you'll be able to deliver working software. If you write code that's hard to read, you can guarantee that it will have bugs in it that you can't fix.

Hopefully you don't have too much difficulty reading code you wrote this morning. That's one reason why writing unit tests is such a good idea: you discover the bugs while the code is still fresh in your mind. But despite all the unit testing, you will still need to change that code next week, or next year. If you want to be able to do that successfully, you'd better make sure you can still read today's code, whether it's next month or next year.

It's also inevitable that someone else will have to read your code. Making your code understandable by someone else is hard work. Coding conventions are no substitute for thought; you must look critically at what you've written, and ask yourself: have I made it completely obvious what's going on here? If you haven't, then you should fix it.

Many other programming principles are extensions of this one. For example, it's a good idea to write Java classes that are responsible for one thing, and one thing only. If you follow this principle, you're on your way to writing readable code. But blindly following principles is not enough. You have to keep asking the vital question: is this readable, not only by me, today, but also by me in six months' time, and also by the newly-hired junior programmer straight out of university in two years' time?

The effort to write readable code never stops, but it's the most important thing we do.

No comments: