Tuesday, March 29, 2011

Test Driven Development

At this point, I guess Test Driven Development (TDD) is old news but while I've always liked the idea and have even made preachy statements about unit tests in the past, I've found it difficult in practice to actually write in a test driven way. I don't mean that I don't always test first, but that frequently when I'm in a rush, I test-never. This has come back to bite me enough that I've gradually started writing more tests when it was easy to do.

I recently came across this screencast of Gary Bernhardt using TDD to create a simple string calculator. Gary's velocity is super impressive, but more importantly the video shows how fast TDD can be, especially with a good key mappings to run tests and a split screen.

I watched this at a good time because at Springpad we've recently started a new project all in python. After reading some more about TDD, I've been trying to make a habit of this style of development. So far it's been great. I think the big advantages for me so far have been:

  • Better than a compiler: especially in a dynamic language these are key to make sure you don't have any spelling mistakes or stupid problems. But they're so much better too obviously. Why check that the method exists, when you could check that it behaves as expected before runtime.
  • Staying out of the debugger is fast: Since starting this, I've tried to write enough tests at the right level such that I don't need to debug the program ever. And I've been mostly successful which for me has really sped things up.
  • Deeper understanding of the codebase: Since you spend more time thinking about behavior not only of your code but also of libraries that you use so that you can test it right, you end up knowing the code a lot better. Seems obvious in retrospect, but I didn't start TDD for that reason.

  • I think there's still a lot to figure out with this. Should you use mocks versus stubs? Does a test belong in a separate integration suite versus the unit tests? Etc. So far I haven't created any strong opinions on this, but I'd love to hear anyone's thoughts on how it should be done.