Invariants on interface properties?
hey guys,
it's me again. today tried define contracts on interfaces. thus, it's working methods, got problems on properties, i've defined on interface.
let's consider interface/contract-class pair:
here defined object invariant in contract class interface. now, if let class implement interface, static checker doesn't seem know object invariant. can have private setter on "balance" , say: "balance = -1" , works (static checker doesn't warn), should not allowed due invariant...
any suggestions/comments on that?
thanks, matthias
it's me again. today tried define contracts on interfaces. thus, it's working methods, got problems on properties, i've defined on interface.
let's consider interface/contract-class pair:
[contractclass(typeof(contractforiaccount))] | |
public interface iaccount | |
{ | |
float balance { get; } | |
bool withdraw(float amount); | |
void deposit(float amount); | |
} | |
[contractclassfor(typeof(iaccount))] | |
class contractforiaccount : iaccount | |
{ | |
[contractinvariantmethod] | |
protected void objectinvariant() | |
{ | |
contract.invariant(((iaccount)this).balance >= 0); | |
} | |
float iaccount.balance | |
{ | |
get | |
{ | |
return default(float); | |
} | |
} | |
bool iaccount.withdraw(float amount) | |
{ | |
contract.requires(amount > 0); | |
return default(bool); | |
} | |
void iaccount.deposit(float amount) | |
{ | |
contract.requires(amount > 0); | |
} | |
} |
here defined object invariant in contract class interface. now, if let class implement interface, static checker doesn't seem know object invariant. can have private setter on "balance" , say: "balance = -1" , works (static checker doesn't warn), should not allowed due invariant...
any suggestions/comments on that?
thanks, matthias
hi matthias,
object invariants not supported on interfaces @ moment. can see why might handy though.
at moment need specify property invariants writing pre-condition on setter , post condition on getter (or on getter if don't have setter).
so in case, become:
float iaccount.balance |
{ |
get |
{ |
contract.ensures(contract.result<float>() >= 0.0); |
return default(float); |
} |
} |
now, force implementation of getter prove non-negative. how can getter non-negative time. well, have add invariant on backing field balance implementation.
thus, writing ensures on getter, may force implementor have invariants indirectly.
cheers, -maf (manuel fahndrich)
DevLabs > Code Contracts
Comments
Post a Comment