Let’s say I have this one:
[Pure]
public static TimeSpan Seconds(this int i)
{
Contract.Ensures(Contract.Result<TimeSpan>() == TimeSpan.FromSeconds(i));
return TimeSpan.FromSeconds(i);
}
Is that right that I ensure the contract result in such strict way, or it is unneccessary?
And in this case?
[Pure]
public static T IfTrue<T>(this bool b, T value)
{
Contract.Ensures(Contract.Result<T>().Equals(b ? value : default(T)));
return b ? value : default(T);
}
My questions are:
- Am I right when indicating such precise contract ensurance?
- Am I obligated to make such strict contract ensurances and why?
- Is it okay, that my contract ensurance repeats (in many cases in my application) the
returnstatement?
Think about the word “Contract” – what do you, in writing your code, wish to guarantee to your callers (or for
Requires, what do you want them to guarantee for you).For trivial examples such as the ones you’ve shown, I can’t think of much you’d want to include as a contract. Maybe for the first, I’d go for:
I’ll guarantee to my callers that I’ll produce a positive result. Obviously, this similar contract could be given if I included more complex mathematics inside this method. I’ll give guarantees on the range, but I won’t guarantee exactly how the result is computed (since that may be subject to change).