Reputation: 9800
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:
return
statement?Upvotes: 4
Views: 1091
Reputation: 239814
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:
[Pure]
public static TimeSpan Seconds(this int i)
{
Contract.Requires(i>0);
Contract.Ensures(Contract.Result<TimeSpan>().TotalSeconds > 0.0);
return TimeSpan.FromSeconds(i);
}
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).
Upvotes: 4
Reputation: 37790
Method purity means, that method call does not causes any caller visible side-effects to object state. That's all.
Of course, pure method can be public, and can define its own pre- and post-conditions. It depends on concrete method use-cases.
Upvotes: 0