Putting the Three Rules of TDD Into Practice

I've been thinking alot lately about how to practice better at software development. One of the things I want to get really good at is unit testing. I think unit testing is vital to the success of a software project. Good unit tests can reduce your overall debug time and can help give you confidence that your code changes aren't breaking anything. However, as anyone who has written more than four lines of code can attest to, writing unit tests is similar to eating vegetables or working out. You know it's good for you and can pay huge dividends in the future, yet we still don't do it.

So, the obvious question here is: if unit tests are so good, what is stopping us from writing them? Assuming that we can go ahead and agree to the assertion (see what I did there?) that unit tests are indeed helpful and worth writing (which is a controversial statement in itself), I think the main reason developers neglect writing tests is due to a lack of standardization. Developers just don't know where to get started sometimes. When do I write tests? How many tests do I write? When do I run my tests? What if I know a change works, do I write a test for it anyway?

This is where Uncle Bob's article can really help us out. Here, Uncle Bob outlines three very specific rules that can clear up any of the questions you may have been struggling with.

The Three Rules of TDD

  1. You are not allowed to write any production code unless it is to make a failing unit test pass.
  2. You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.
  3. You are not allowed to write any more production code than is sufficient to pass the one failing unit test.

At first, trying to follow these rules is going to be pretty tough. Very tough actually. I'm still trying to get into the test-first mindset and it's going to be difficult to break away from all those years of doing development a specific way. However, I know that this is an area of development that I am weak in, and anything I can do to improve how well I write unit tests is welcome.

Ready to get started? Uncle Bob suggests checking out The Bowling Game Kata. Check it out and let me know what you think.