Monday, July 09, 2012

What Uncle Bob won't tell you about TDD

If you never maintain code (written by yourself or others), please ignore this blog post.

Let's imagine you're about to make some changes in an existing product. The product was developed by following strictly The Three Laws of TDD (Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin p.122).
First Law You may not write production code until you have written a failing unit test.
Second Law You may not write more of a unit test than is sufficient to fail, and not compiling is failing.
Third Law You may not write more production code than is sufficient to pass the currently failing test.
And you decide to follow exactly the same laws to finish the requested changes. The laws become The Three Laws of TDD for Changes
You may not change production code until you have written, or made an existing passed unit test, a failing unit test.
You may not write, or change more of a unit test than is sufficient to fail, and not compiling is failing.
You may not change more production code than is sufficient to pass the currently failing test.
Check all the related somethingShouldHappenIfThisHappens tests and make them fail one by one with the changes you're working on? Or forget the TDD laws, make changes to production code directly and see which tests turn red, then review those tests?

TDD helps the design of the outermost layer (ask a junior and a senior developer TDD same story and you'll see almost the same public interfaces in production code, but very different implementations inside) of an application. But test cases are instances of requirements (again, ask a junior and a senior developer TDD same story and you'll see very likely they capture different instances from same requirement), and by no means are the requirements themselves. Can't agree more with Cédric on tests are not specs.

Requirement changes everyday, so it's easy to try if The Three Laws of TDD for Changes works.