What Is Test Driven Development

Time to go basic again. Let’s talk about TDD.

Test Driven Development has been practiced for a while. One of the practices in Extreme Programming was Test-First (more than a decade ago):

Code the unit test first.

Sounds simple enough, but there’s a whole process around it. Here’s a nice picture to explain it:

image

Here’s the recipe: Write a failing test, write the code that makes it pass and refactor.

What makes TDD so important that it was a core part of XP? Quite literally it changes the way you code.

Think about how you do it today: You need to add a feature. So you jump right into the code, hacking what’s needed, taking the necessary risks and you have a (more ore less, usually less) working feature.

But with TDD you introduce a disciplined incremental process that has built-in feedback into it. That’s how you write quality software.

You start with a small, focused test. Usually, it’s around a class, or even a method. For example, here’s a first test for a Mailbox object (that doesn’t exist yet):

Let’s see what we have in our very short test:

  • A name that describes a scenario of how the object is used
  • A name for the object – that other programmers can understand. With a proper name, you convey expectations.
  • Method of creating of the object – a simple constructor. It doesn’t need dependencies (at this point)
  • Default behavior of object – returning zero on an empty.

With writing the test first, we actually describe the object to others, in terms of interface and behavior. Working this into a process, we’re adding more functionality incrementally, in small doses, and we know all the time that what we’ve coded before still works.

Unit tests give you a safety net around your code, so if you break something, you’ll know immediately. TDD is taking this further, wrapping the entire code with the safety net. Just follow the simple procedure above!

Well, it may seem simple, but still, most people don’t do TDD. There are a whole lot of bumps in the road that you should be aware of starting out.

Ah, If there was somewhere to go and learn this stuff…

Wait, there is!

Join me in my “Introduction to TDD” webinar next week, and learn more. We’ll talk about do’s and don’ts, benefits and pot-holes, and code a few simple and real-life samples.

Register now!