I am a somewhat defensive programmer and a big fan of Microsofts Code Contracts.
Now I cannot always use C# and in most languages the only tool I have is assertions. So I usually end up with code like this:
class
{
function()
{
checkInvariants();
assert(/* requirement */);
try
{
/* implementation */
}
catch(...)
{
assert(/* exceptional ensures */);
}
finally
{
assert(/* ensures */);
checkInvariants();
}
}
void checkInvariants()
{
assert(/* invariant */);
}
}
However, this paradigm (or whatever you would call it) leads to a lot of code cluttering.
I have started to wonder if it is really worth the effort and whether proper unit test would already cover this?
Best Answer
I don't think you should think of it as "vs".
As mentioned in comments by @Giorgio, code contracts are to check invariants (in production environment) and unit tests are to make sure you code works as expected when those conditions are met.