Saturday, May 17, 2008

Use examples to make your code easier to understand

Programmers are used to abstract thinking. To program is to generalize: A method is a general specification of what to do during execution. A class is a general specification of objects. A superclass is a generalization of several classes.

Altough our minds are capable of abstract thinking, concrete thinking is much easier, and concrete examples are the foundation for abstractions. For instance, when we were children, our parents didn't try to teach us about cars by explaining to us cars are and what they can do. Instead, they just pointed at a car that was driving by and said ”Look, a car!” When they had done that a number of times, we knew what a car was.

Another example is prejudice. We all have prejudices, because this is the way our minds work. If we have met a few people from Denmark in our lives, and those people were friendly, we ”know” that Danes are friendly. And this works even stronger for negative prejudices.

My point is that we learn by examples. Einstein said that examples is not another way to teach, it is the only way.

As programmers, we are highly skilled in abstract thinking and expressing ourselves in programming languages. But when the code becomes too complex, we try to comprehend it by making examples in our minds of what the code would do in different circumstances. We imagine or write down the values of different variables and what the behavior of different tests and loops will be with those values.

And when it becomes too hard to imagine what is actually going on by reading the abstract code, we use debuggers for help. A debugger is not abstract. It gives a concrete description of what is actually happening at runtime. It gives information on how methods execute in specific instances and which objects exist at a specific moment. This concrete information is so much easier to understand than the abstract code.

Therefore, it's a good idea to design concrete examples of objects and scenarios before implementing the abstract classes.

Unit tests are exactly such examples. They make it easier to understand what happens at runtime. And a well designed unit test is the best way to explain to somebody what the code does. If you ever had to take over somebody else's code, you know how hard it can be to understand it. Where do you start? Unit tests is a good place to start.

So, my suggestion is to think of unit tests as documentation. Write unit tests that are easy to read and that explain the intent of the code.