blog.onlysimpler.com

A blog... only simpler.

Readable Code - 30 May 2007

Why do so many developer's insist on writing horribly unreadable code? I think it's because they're just plain lazy!

Ok, perhaps that's a little harsh. Maybe it's more correct to say that most developers write unreadable, messy code because they don't see the point in doing any different.

"It's only going to be read by a computer right? And a computer can read code no matter how messy it is so why bother?". Sure, a computer might be able to read it, but people wont!

One of my favorite quotes from this book is - "programs must be written for people to read, and only incidentally for machines to execute". I couldn't agree more.

How many times have you written code that worked first time and never had to be changed again? Probably not very often. The bulk of a piece of code is typically written in one sitting. But it's re-visited over and over again. Every time a defect is found or an improvement is made, some poor sucker has to read the code and figure out what it's supposed to do. And here's the thing... at some point that sucker is going to be you!

Even if you were the original author, chances are you're not going to remember what it does or how it does it. So that leaves you with one option - read it and figure it out.

Here's where things get interesting. If the author bothered to take the time to do things right and write clean, clear, commented code then this can be a simple and pleasant experience. However, if he just cobbled it together because he had to go home and was running late for his train, it can be far from pleasant. What should have taken you a couple of minutes to read and understand can end up wasting an entire afternoon and do terrible things to your blood pressure in the process.

So what do I mean when I say "readable" code? I don't want to get into religious debates on tabs vs spaces or whether to put braces at the end of a line or on the next. That's really not that important. What is important is to write code that is easy for others to read and understand. Here are a few things to consider...

Basically it all comes down to taking a little pride in your code. You should be able to look back at code you've written and be proud of it. Not only will it make your life easier when you need to re-visit the code, but it will benefit the whole team. If you spend the time doing things right in your code, pretty soon you'll see the external effects of a more solid, reliable and bug-free piece of software.

link