Test-Driven Development

In my recent side-project, Cpp-Markdown, I used a testing suite (developed by the author of another Markdown translator) as a guide to see what I needed to work on next, and to immediately show me when I broke something. It was a very nice way to write code… I could always see progress, and I always knew where bugs must be so I spent far less time in the debugger. Working from a testing suite and having a repository of all recent changes was like saving a game before doing something dangerous — I felt free to try anything, because if I totally screwed something up, I always knew about it within minutes, and could always easily go back to the last fully-working copy.

It was so nice, in fact, that I was reminded of a previous attempt I’d made at it, and I decided to further study the idea of Test-Driven Development (a.k.a. TDD). As luck would have it, I had also just started a new phase on Project X, one that TDD would be very useful on, so the decision to use TDD on it was a no-brainer.

The basic idea behind it is:

  • You start by writing a very simple test for whatever feature you want. Then you run that test, to prove that it will fail as it should. This is the red phase. Check it in.

  • Next you write the new feature code, just enough of it to pass the test, and run the test again. When the test passes, you’re finished with the green phase. Check it in again.

  • Finally, you go back and tidy up the code, eliminating any now-redundant parts and making it generally nicer. Run the full testing suite on it after each change, so you’ll know that no other bugs have slipped in, and check in the code every time the test suite says it’s okay. This is the refactor phase, which you might need to do several times to get the code to a satisfactory state.

  • Repeat the red, green, refactor cycle for the next thing you want to implement.

If you follow those steps and the The Three Rules of TDD, you apparently get near-magical results. From the “three rules” page…

[…] Indeed, I had been a programmer for nearly thirty years before I was introduced to TDD. I did not think anyone could teach me a low level programming practice that would make a difference. Thirty years is a lot of experience after all. But when I started to use TDD, I was dumbfounded at the effectiveness of the technique. I was also hooked. I can no longer concieve of typing in a big long batch of code hoping it works. I can no longer tolerate ripping a set of modules apart, hoping to reassemble them and get them all working by next Friday. Every decision I make while programming is driven by the basic need to be executing again a minute from now.

So over the past couple days, I redesigned the new part of Project X so that I could work on it using TDD. I have high hopes for it. We’ll see how it goes.

2 Comments

Comments are closed.