January 22, 2005
First experience of test driven development
The basic idea behind TDD is that you write a test before you write the tested code. You don't write all the tests for a program before you start. Rather you alternate between writing a test and then writing just enough code to make the test pass. Then to clean up, you refactor the tests and the code, testing again after each step. The technique is highly iterative. In most cases, each iteration takes no more than a couple of minutes and you modify only a few lines of code.
I don't want to go into much detail because I am still at the beginner stage and I am sure there are some things I have got wrong.
The way I went about it was to rewrite a program I wrote a few weeks ago, this time using TDD. I used Visual C# 2005 together with NUnit. I configured the project to automatically run NUnit after every build.
The tangible benefits I have seen so far are:
- I have unit tests to test absolutely every line of code in the program.
- This means I can refactor liberally with confidence that I haven't broken anything.
- When I add a new feature, I know I haven't broken any of the other features.
- The unit tests extend the idea of self-documenting code. But rather than documenting how the program works, they demonstrate how to use it.
- There is no danger of this documentation getting out of sync with the code, not even for a few minutes.
- The TDD techniques lead naturally to more robust code.
- The tests force you to organize your code in a modular way and refactor regularly.
- Writing tests first actually helps you design. It helps you look at your code from the perspective of its users. And I believe it will lead to better designs.
- I didn't need to use the debugger even once. Usually when I write a program, I spend more time debugging than programming.
Even at this early stage, I would encourage any programmer to try it out. The benefits are apparent even writing a program that is only a few hundred lines or so.
I'll be writing an article on TDD on my web site in the next few days, but, as you demonstrated, there really isn't much to it to at least get started.
Keep us updated on how it goes and what you learn along the way.