Every once in a while in my development career I realize just how much I've been missing out on some technique that I've just discovered. Such was the case with learning about Design patterns , as was the case with learning how to write self-documenting code, and countless other occasions where I felt I've “discovered a whole new world” and from that moment on tried to stick to the new things I've learned. Doing Test-Driven development (TDD) was definitely one of those techniques.
I touched it first when I discovered the notion of eXtreme Programming. XP is a software development methodology that has some hardcore guidelines on how to achieve success in development projects but it's a very steep learning curve, and you can find plenty of books nowadays that talk about this subject. TDD is one of the trademarks of XP (you might have heard about other, more “provocative” notions such as pair-programming) but it wasn't invented there. There's a whole movement that supports what is known as “Agile methodologies”. You might find it interesting to explore this whole subject. A good start would be Martin Fowlers' site, one of the granddaddies of everything that is agile.
But I digress. The whole notion of TDD is just that. Development is based on testing. Does that sound weird? That's because we're used to it being the other way around. Usually we'll code something and throw it over to QA for testing. Sometimes we'll hack out some tests after the code base is done, just to make sure that “everything appears to be working” . TDD takes this whole process and turns it upside down. That means that whenever we are going to code something up, we stop, and first do a test that makes sure our code works. Yep. We don't have any code yet. But we have a test to prove it.
Here are the bullet points for how to start doing TDD:
- Make a test that fails
- Make it work
- For every new feature goto step 1
It's that easy. Really . Now, I know this sounds weird at first. How can we test code that does not exist yet? Well, if our code even fails to compile, that means the test failed in our book. So it's a start.