Assuming all new .NET 4.0 code
I see that there is the option to turn them on. However I don't see what the best practice is?
Is the best practice that once static checking is done, you really don't need to do runtime checking (since the compiler makes sure that the conditions are met)? Or are there scenarios where even though the compiler checks it for you, it is still possible that during runtime the condition will not be met?
Any good online discussions or articles on this. I see many that explain how to do either but not many that explains which is the best practice assuming all new .NET 4.0 code with no backwards compatability needed.
since the compiler makes sure that the conditions are met?
It will be very rare that the static verifier will be able to verify the whole application. We will usually settle for the major parts.
Should I turn on runtime checking of code contracts for .NET 4.0 on release builds?
Probably not the Full option, but one of the lighter ones like PreConditions Only.
For performance critical code you may want to turn them off entirely.
It depends on the way you use Requires.
If you use 'Custom Contract Requires' mode:
public void SomeMethod(SomeClass x)
{
if (x == null) throw new ArgumentNullException("x");
Contract.EndContractBlock();
...
}
you may safely turn run-time checks off, and keep your error checks and exceptions
If you use 'Standard Contract Requires' mode:
public void SomeMethod(SomeClass x)
{
Contract.Requires<ArgumentNullException>(x != null);
...
}
you should turn run-time checks to at least 'ReleaseRequires' level. Otherwise you'll loose all error checks and may get unexpected exceptions (e.g. NullReferenceException
somewhere deep in the code instead of ArgumentNullException
on the public surface)
I wouldn't use higher levels of checking for a very simple reason: if any contract other than Contract.Requires<E>
fails, the runtime will throw a System.Diagnostics.ContractException
which probably will not please users.
BTW, Henk Holterman is absolutely right that static verifier is limited and you shouldn't rely on it completely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With