
TDD stands for Test Driven Development. In Test Driven Development, a programmer looks at the specifications he is given and begins by writing tests that his software must later pass. It is backwards from what we’ve learned so far and sort of feels like writing with your left hand.
Here is a classic coding problem called FizzBuzz: Given a number between 1 and 100, return the number as a string (meaning, return it as a word with quotation marks rather than a naked number). If the number is divisible by three, return “Fizz.” If the number is divisible by five, return “Buzz.” If the number is divisible by both three AND five, return “FizzBuzz.” This sounds complicated to a layperson, probably, but most programmers do stuff like this (and much worse, complexity-wise) all day.
To solve this problem normally, I would just start jotting down things I need on a sheet of paper. At this point in my study, I could probably sleuth this one without much sweat (not the case three weeks ago). I would write down some code with some conditional clauses to make sure that all my Fizzes and Buzzes showed up at the right time and then click the “Run Test” link.
But in Test Driven Development, we start with the tests. So, instead of staring at the screen wondering where to start, we write a simple test. The FizzBuzz Method, if given the integer 1 should return “1.” So we make a test that looks like this:
Assert.AreEqual(“1”, testerForFizzBuzz.FizzBuzz(1);
This code is basically saying, if the integer 1 is fed into the method, “1” should be returned. It’s as easy as it gets. We write the code to pass the test and nothing more.
Then we move on to 3. If three gets entered, then we should return “Fizz.” So we go above the place in the code where we returned “1” and write that if the integer is 3, we should return “Fizz.”
And we keep going. Specification by specification and test by test, the code is built.
It’s easy to overwhelm your brain while trying to hit all of the specifications at once. But TDD requires that you break it up into simple, little decisions that are hard to screw up.
I was skeptical during Tom’s lecture, but I really came to enjoy it. I put in a twelve hour day today and drove home with a smile, thinking of Fizzes and Buzzes.