I found an interesting link today from Mario Gleichmann called Test Driven Development and Design By Contract – friend or foe?. I’ve always been lukewarm toward Design by Contract (DbC). Occasionally I’ll run into claims from DbC enthusiasts that using DbC completely eliminates the need or desire for Test Driven Development and I’ll start rolling my eyes. That attitude stayed perfectly intact until I spent some time with Greg Young at DevTeach talking about spec#.
After learning a bit about spec# I can see plenty of value for DbC, but certainly not as a full replacement or even an alternative to TDD/BDD. One way or another it’s all about specifying the desired behavior and using some sort of automation to check that the specification is being satisfied. What I envision is using DbC to efficiently knock down a lot of the boring problems like erroneously passing nulls around at compile time. I would still use TDD/BDD to get to the interesting part — the actual behavior of classes and methods. Greg is claiming that having spec# would replace 2/3 of his unit tests with more declarative DbC style specifications inside the code with arguably a faster feedback loop than running NUnit tests. All I can say is “cool.” Cutting down feedback cycle time is always advantageous. Eliminating tedious imperative code with declarative specifications is definitely good.
I’m not a fan of copious amounts of defensive programming being anywhere but externally facing API’s. I don’t write a lot of unit tests checking for bad data coming into or out of methods because I don’t see that activity as having a positive reward to effort ratio and I can’t abide clutter in the code. I haven’t particularly recognized any real pain from not writing these unit tests, but if I did feel that pain, I’d rather just use DbC specifications in the code and get going with the more interesting work.