A Little TDD
Test-Driven Development (TDD) is a novel software development technique. With the ‘traditional’ software development process, we write the code, debug it and then write unit tests.
TDD works differently – we write the tests first and then let them ‘drive’ the implementation of the code. So how does this work?
OK. We first write a unit test that requires new behaviour from our code. Since this behaviour does not yet exist, the unit test is failing. Next, we write just enough code to make the test pass. Then we write the next test and make that pass. And so on.
TDD reduces non-essential complexity in our systems. In other words, the developer-introduced unnecessary complexity that results in messy code is absent in projects developed using TDD.
It does take a little while to get proficient at TDD. Does that mean we shouldn’t try? No, of course not. Good things take time.
OK. I do want us to write a little bit of code using TDD today. So let’s get started.
Let’s assume we have a requirement to create the code for a shopping cart. Customers can put items into the shopping cart as they shop. When they are ready, they can pay for the contents of the cart at the checkout.
Let’s create a ShoppingCart class.
How do we write the first unit test when we don’t even have the class yet? What do we do to get started?
How about this unit test.
The red squiggly underline is my Integrated Development Environment (IDE) pointing out that it does not know about ShoppingCart. No surprise there. We haven’t written it yet!
Since the IDE is confronting us with a compilation error, we have our failing test. In TDD, compilation errors are test failures.
Now it is up to us to make the test pass. How do we do that?
Well, we write the code for the ShoppingCart class. The least amount of code that we can get away with to pass the test:
As you can see below, the red squiggly line has gone from our test; the code compiles.
And if I do run the unit test, it passes too:
We have completed our first test!
I hope you’re intrigued about TDD. It is a technique that takes a while to get productive. On the upside, TDD done right does generate simple code that is easy to understand and easy to maintain. However, it might just be a worthwhile investment. Especially when you’re sitting in your seat in a thin cylindrical metal tube moving at 1,000 km per hour 10 km above the surface of the Earth, and you hope that the software controlling the plane doesn’t look like most of the messy brownfields codebases you have seen.
I hope you’ve enjoyed this first step on our journey to learning TDD. I’ll continue adding new ideas and practices regarding TDD over time. And, of course, we’ll be extending this example of our ShoppingCart further.