I have moved my active blog over to tumblr. I've maintained this blog for reference but will be posting to http://www.robustsoftware.co.uk instead. I've pointed my Feedburner feed to tumblr so if you're subscribed already you should already have switched with me.

Test aided development

I make no secret of the fact that I'm a fan of using unit tests as part my development process. I am the example of a test infected developer. The problem I have is conveying the benefits to the people I work with in order to get them aboard the testing train.

The main problem is that writing tests is hard. Sometimes very hard. When you start you have to get your head around a unit testing framework, mocking and perhaps even interface based development. Then you have the hurdle of taking 5 minutes to write code that previously took you 30 seconds. You feel like you are robbing your employer of productivity. I think this feeling of guilt could be one of the main reasons people don't stick with tests aiding their development.

Notice I have not at any point mentioned writing your tests first. Though I feel this is the most effective way of using tests in your development; it does require a large change in the way you think. I'm happy to leave out yet another barrier to the uptake of test aided development.
So what's so great about having tests as part of your development?

One of the simplest is that you can have more confidence changing the code you have tested. If you know that most the logic in a section of code is covered by tests you can be more confident changing code in and around it as tests should fail if you break something.

Another benefit is that you get a feel for when your code is doing too much. This will come from your tests being hard to set up. A method might only be 6 lines long but if you have to set up 5 dependencies to test it you know something's wrong. You probably wouldn't notice this sort of thing without having to write the test. Similarly if you have to set up 10 tests to cover all the paths through a method too much is going on in that method and it needs refactoring.

Following the forces of these extra sources of pain will aid you to produce code that is well factored and easier to debug. How is it easier to debug you may be thinking. Well if your code is easy to test each method will be doing very little making a stack trace even more useful than normal. Also reproducing a bug through a test should be easy as your code will already be easily testable. Every developer knows that once you can reproduce a bug you're 95% of the way to fixing it. The test will also remain as a safeguard against the bug reoccurring.

Using unit tests in your development is not only about testing itself. It is about having another source of information on the quality of your code. The benefits of the suite of tests remaining after are just a great side effect.