Tuesday, 11 December 2007

Code Should Mean Something

Dear Junior
There are always many discussions on the aesthetics of code and coding.
I thoroughly believe that code should have a meaning. By that, I mean that the code does not only execute something. Rather, it should go beyond that and try to reflect the idea of the programmer that wrote the code. As a reader, I should be able to reconstruct the most crucial ideas that lead to the solution I see in front of me.
In other words, the main purpose of the code is to explain your idea across time and space to another programmer, which might be yourself when you have forgotten all that extra information you have in your head. To your help you have a very restricted (programming) language in which you should make all your important ideas clear. Apart from that, you are only allowed to annotate (documentation) the solution with text in natural language.
In this respect, programming is a pedagogical trait.

Wednesday, 5 December 2007

Don't Test Your Code

Dear Junior

From time to time I get asked how to test a specific piece of code (EJB2:s or Action classes being nasty examples). Most of the times I spontaneously do not want to answer the question at all, because I think it lead us in the wrong direction.

I do not want to test my code; I want to test the behaviour of my code. The distinction might seem like hair-splitting, but I think it makes an important point. For example, if I have some order payment service I want to check that the payment information is well-balanced, that a payment request is sent to the bank, and a lot of other stuff. If we "test the code" we want to ensure all of these things as they are written.

However, if we focus on testing the behaviour we want to make sure that one idea ("generated book-keeping transaction is well-balanced") is correctly realised by the code. This approach enables us to focus on one aspect of the behaviour at a time and ask: How can I make it possible to test this behaviour. And the natural answer is to restructure to obtain testability.

So, phrasing the test-question "how do I test my code" leads us to build really elaborate testing frameworks to feed test data into the database, and then running our components in a production-like environment (e g Cactus tests). On the other hand, phrasing the question "how do I test the behaviour of my code" leads us to refactor until we have separated concerns to such a degree that each idea is possible to test in isolation.

So, don't test your code; test its behaviour.



ps One thing you can do if you redesign for testability, is that you can refactor your code to require less cumbersome and awkward mocking.