TDD - Test Driven Development

I have done almost nothing related to the project last week - the main reason being, unfortunately, a lack of time and tiredness in the few free moments. This wasn't the only reason, though. I managed to start trying to write code a few times, but then I was realizing that although I have a general vision for the future of the project, I don't really know where to start and how to quickly get something executable and testable (and the possibility of testing the code is a huge motivator). I've decided to try to overcome my creative blockade using TDD - Test Driven Development.

The idea behind TDD is pretty simple - we start coding by writing tests. We add a test, which initially won't even compile, because the code that is supposed to be tested doesn't even exist yet. When we have the test, we write some proper code - just enough to get the test to pass. When we see green color in the results, we refactor the code (if there is a need for that) and go back to writing the next test.

This approach has numerous advantages:

  • We achieve a full or almost full test coverage of the code, because we never add code if we don't have a failing test.
  • It's easier to focus on defining a convenient API - a test is basically a piece of code that uses the API provided by the tested code, so when we write it, we already know whether the API is easy to use and we can modify it in case it's not.
  • A part of the above advantage is that we write cleaner code - the tested code has to have appropriate structure in order for testing to be possible at all, and it usually makes future modifications easier.
  • Finally, the thing I hope will help me - we immediately get some executable code that uses the library (if we are writing a library), so we can (or even must, actually) run it and see how the code is doing.

There are, of course, some disadvantages as well, the main one being for me that to a programmer not used to TDD (so one like me :p) such an approach isn't very intuitive and one has to be careful not to go back to writing the functional code first.

It's already late today, but tomorrow I should have some time to try this idea out and see how it works in practice. I also hope to have something for a next blog entry then. Until tomorrow, then!