Test Driven Development and Design by Contract
Saturday, August 16th, 2008I have to admit first that my first idea about this article was going to me a rant about how TDD goes well beyond what design by contract gives as I felt Bertrand Meyer in computer magazine dated August 2008 missed that point. Then I thought better of it and checked for resources through google and discovered that I am late to the party with at least three very intersting articles on thus very subject: DbC and Testing, more on TDD vs Design by Contract and Test Driven Development and design by contract, friend or foe. On the other hand I did not find a tool that was satifsfying to link TDD and DbC (don’t you love acronyms ?). So here is my attempt at a story describing what I would like.
Let’s imagine the following scenario. I need to write the function f of a service S.
That function will take an id and a number as input, find an object responding to interface O from a cache responding to interface C.
In a TDD manner I start writing the test. Discover in the process that S needs to know about a C. Stubs a C for the purpose of returning an O to my service. There I specify that the contract of the find message of C is that the passed id is not null, it returns a non null O or throws a NotFound exception.
Now I would like that the calls to the C stub would verify that contract to ensure I am testing in accordance to the contract. This way if the contract changes in a way that is incompatible with my assumptions, my test will break and signal the problem.
I would further like the contracts to be verified automatically against the instances of implementations of C throughout my development cycle. And I would like to be able to selectively keep the contract enforcement in my deployed product.
The net result is not to get rid of the defensive programming but to move it into a well defined area as a specific concern that crosscuts my software. I would even have the choice to test whether the contracts actually specify what I intended. It would also remove the necessity to test the defensive programming code in the same artefact as the functional code.
Why all that ? Because TDD, beyond creating regression test artefacts also is a way to specify the component being created and that therefore it would be nice to be able to capture in separate, executable artefacts the implied specifications made on the related components.
Anyone knows about such a tool ? Anyone wants to write it ? Am I crazy ?
