February 6, 2007

Test Driven Development

Over the past, oh, year and a half or so, I’ve followed the rapid ascension of Ruby on Rails to the top of the web development heap. In the process I read a lot of blog entries, a lot of “Hello World!” introductory articles and a lot of best practice documents. A big part of the thinking behind Rails is Test Driven Development (TDD) – the idea that you should write automated tests before writing code to make sure that a) you know what the code is supposed to do before you write it and b) once the code is working there is a quick, easy way to make sure it keeps working as you further develop your application.

I never really had a chance to try TDD until recently. I started working on a project at work that isn’t part of any of our old projects – I got to start something brand new. So I set out to use TDD from the start and I must say that it’s going quite well. Writing the tests is forcing me to think carefully about the interfaces of my classes and to separate the project into more atomic parts than I might otherwise.

I’m using JUnit and have an Ant build file set up so that the default target depends on my unit tests. I can see very quickly if a change I make to the code makes things work or not. I don’t have to mash together a driver program to exercise my work and then throw it away once it finally works. Sure, I write code to test, and that’s analogous to a driver program, but the key is that the test will stick around after I’m finished with it for the time being and the work that I do to test my work for correctness won’t need to be repeated by someone else when the program needs to evolve. The tests make nice example usages too.

I’m a convert.