Friday, September 4, 2009

TDD nails it


Imagine yourself TDD'ing a thermostat controlling a heater. Your first unit test is to set the temperatures in the fake thermometer as well as the Thermostat object, which is the unit under test, and to verify that it actually starts the heater.

Now, in the production code, a TDD beginner will find it tempting to check the temperature and then start the heater. However, the correct thing is to not check the thermometer, but just start the heater regardless of input. This is because this is all that is required to pass the first test. You don't need to check the thermometer before you have a test that would fail if you didn't check the thermometer.

If the TDD beginner followed through with his gut feeling and implemented the check right away and then proceeded to the next feature he would be able to remove the thermometer check, introducing a bug in his software, without any tests failing.

Thus removing the premise to safely refactor and changing without breaking.

TDD nails it.

Now, if you were using hammer and nails to fix a piece of wood (say, a board) in place, a novice could be equally "tempted" to hold the board in place and then just hit a nail in its center before moving on.

This would look all well and good until the forces started acting upon it, in which case the board would quite likely shift out of place.

Now, let us pretend that a piece of functionality is a board and that unit tests are nails.

By using just a single nail, both the piece of functionality and the board would seemingly be held in place by nails, but in reality the real upkeeper for both is friction. Friction on wood surface and friction in the code base. Without neither being be nailed in place.

When I implement a piece of functionality I certainly hope to having "nailed it"!

No comments:

Post a Comment