Sunday, 25 May 2008

Programming for People

I believe that the best piece of programming advice I ever read was "Write your code so it's easy to read."

I've been programming for about 20 years, and I've read advice like "always comment your code" and "choose sensible variable names", but it never really sunk in. I didn't understand the reason behind this advice. Now in the last couple of years I think I finally understand the reason why: Code is written once, but read many times.

It might take you a long time to write a good, solid routine that performs the exact function that you want. And it might take you even longer to write the code so another person can understand it, so you think "why bother?" But at the end of the day, the investment is worth it, because whilst you only write that function once, coders will read that function many many times. And when I say coders will read that function, I'm also including you. You will re-read that function. Whenever you need to perform some maintenance coding, when you need to make a subtle change to the effect of the function, when you need to refactor your code - even when you're just looking through the code, trying to find "that routine that I wrote last week - I know it was something to do with...", you'll appreciate the extra effort you went into to make the code easy to read.

Because I finally came to realise, that if I want to be a good programmer, then I need to write my code primarily for a person to read, and only secondarily for a computer to read!

That was probably a bit of a controversial statement there! But the way I see it, for all but the most trivial functions, if a piece of code is written without human-readability in mind, and there's a bug, it's gonna take a heck of a long time to track that bug down. But if the code was written for a person to read, then it will take a fraction of that time to find the bug, because less time is spent trying to understand the code - the code is amenable to human understanding, and so time can be spent, more effectively, hunting down that bug.

In conclusion:
  • Code is Write Once Read Many
  • Write the code so it's easy to read
  • Code primarily for a person to read, and secondarily for a computer to read.

1 comment:

Anonymous said...

I agree with that