I'm learning how to design by contract by annotating my existing code with Contract.Requires()
and Contract.Ensures()
wherever I can.
After fixing the warnings that were actually caused by me, I started to notice that many methods in the framework do not ensure their post conditions. This concerns me, because the static checker is now giving me false positives about possible violations of my preconditions.
An example of a method that doesn't implement Code Contracts:
CultureInfo.GetCultureInfo(string)
As stated by the documentation:
- Empty input will result in an invariant culture object.
- Bad input will result in an exception.
In no case will it ever return null
. Still, I can't use this:
Contracts.Requires(culture != null)
If I do, the static checker gives me this:
CodeContracts: requires unproven: culture != null
So, what do I do? Ignore the warning and write a comment with a link to the documentation? Or is there a way to prove post conditions for a method that someone else wrote?
edit
Making assumptions seems to make the analyzer shut up, but only until the next time that I write the same line of code.
var culture = CultureInfo.GetCultureInfo("en");
Contract.Assume(culture != null);
MyPreconditionalMethod(culture);
I've looked at the [ContractClassFor()]
attribute, but it requires a mutual handshake. :\