Sunday, March 25, 2012

Test Driven Development == Granting a Wish


In test driven development, if you're doing it right, then you're likely to be writing code that is wrong.

I don't mean that in a bad way, quite the contrary, but it's one of the oddities of test driven development that makes some people run away, fast.

For example, when your'e starting to write tests for some system, the general solution for the first version of the code is to write a function that just returns the value the assert was expecting:

test: assert( Foo( 5,3 ) == 1 )
code: Foo() { return 1 }

.. most people seeing this as a first step laugh, or just comment about how dumb it is. But this element of _the simplest thing that will work_ is often overlooked. It's actually one of the most important things to get hammered into your head as early as possible.

The tests are being tested too

TDD makes you evaluate your tests. This is really important because most software design methods take a problem and design a solution for it. TDD takes an unfinished solution (empty project) and refines it until it works for all tests you can think of.

Which brings me to my point. How many of you have granted a wish?

In Dungeons and Dragons, the wish spell is one of the most annoying and powerful spells in the whole game. It can do anything. Literally, but how the DM grants a wish is up to him. The player has to be very careful about how they ask for what they want, otherwise a completely innocuous request can go awry and could commit genocide.

and so he said, I wish that all traces of the disease was eradicated from the elves. at which point I told them that all the elves caught fire and died.

See, tests in TDD are just like wish spells. You make a test and then you go and do the easiest thing possible. Sometimes it's easier to just burn all the elves / return 1. Sometimes, the test requires better coding. It's the act of refining in TDD that gives it its strength. You can get inspiration for what test to write next from what you did to make it pass last time, and every time you think of something to make the test pass, you can think of a new test that breaks it.

That's how we get to a final working solution. We keep on adding more wishes adding more criteria so eventually you find a way to cure the disease while keeping your elves raw.
Post a Comment