Friday, May 11, 2007

7 tips on writing clean code

The idea with this blog entry is to write up some tips on this once and for all, in the hope that it can help people out there who struggle to write clean code.

The main goal with these tips is readability. This is important because usually your code has to be changed or reviewed by other people, and writing readably makes these people's jobs a lot easier. That may be obvious. What's less obvious is that it also makes your own job easier, because working on simple code is a lot easier than working on complex code, even while you are writing it, and the more readable code is always simpler.

An important part of making your code readable is to always work to communicate your intent. The basic idea is that it's usually not difficult to see what a single line of code does. The tricky thing is to see why it's doing what it does. So the more you can make your code communicate the thinking behind the code, the better it is. You'll see this point recurring repeatedly below.

I should add that most people seem to be aware of most of these rules, in a general kind of way. The main point of this posting is really to convince people that these rules are important. So important, in fact, that you should try to always follow them, and that you should have a really bad conscience about any code that breaks them. So bad that you just never write any such code. Some of these rules require you to write a little extra code, but I think I can claim that none of them cause you to actually lose time, on any project.

1. Always know why you are catching an exception

2. Never declare implementation types

3. Use descriptive variable names

4. Cut-and-paste code

5. Variables and communication

6. Don't preserve return values you don't use

7. Omit needless code!

0 Comments: