I just
watched this amazing PDC presentation (the most impressing I saw so far):
Contract Checking and Automated Test Generation with Pex by Nikolai Tillman and
Mike Barnett.
It is
talking about .NET 4 support and tooling around contracts. I strongly encourage
you to take an hour to watch it. .NET 4 will come with a contract API, System.Diagnostics.Contracts,
much more compelling than the simple (yet very useful)
System.Diagnostics.Debug.Assert(…). What is not said (unless I missed it?!) is
if there will be some tooling to transform automatically existing Debug.Assert(…)
within the new contract API calls. I hope so! The code base of NDepend contains currently 3 470 calls
to Debug.Assert(..) for 69 256 lines of code.
I take a
chance here to praise the usefulness of contracts and more specifically of
Debug.Assert(…). I always felt that there is too much emphasis in the community
on automatic testing compare to contracts. For me, these 2 correctness
techniques are equally efficient. And actually, what the presentation shows
well thanks to the super-promising Pex tool,
is that automatic testing and contracts are 2 sides of a same discipline that
consists in finding code defects automatically. Pex will promote contract
amongst automatic test addict developers and that is a good thing. As a side
note, I explained in a previous post why and how Debug.Assert(…) checking must
be activated during automatic tests run.Unit Test vs. Debug.Assert()
My feeling
has always been that automatic tests
and the code itself are 2 different
ways to express the same thing: how a piece of code should behave. Code tells
the machine how to do it, step by step
(do this to compute result from an input) while automatic tests represent a more declarative
way of saying what the code should do (this result must be
computed from this input), what can be seen as specification. Generating automatically tests from code, this
is the job of Pex, makes sense because as just said, the code already
contains enough information needed to test it. There is a problem however: if
the code contains some behavior defects, Pex will generate flawed specification.
This is why contract are needed, to assert specifications that cannot be inferred
from the code and see if the code abides by the contracts rules.
Bets are open:
C#5 will come with some syntax sugar that will generate IL code that will call the .NET 4 contract API under the hood, a bit like the using {…} syntax sugar calls the IDisposable API.