Date post: | 15-Jan-2015 |
Category: |
Technology |
Upload: | einar-host |
View: | 859 times |
Download: | 2 times |
ms code contracts
eih
what is
a code contract?
caller
callee
contract
bool Equals(object o)
a weak contract
what is
design by contract?
“Unless design by contract evokes images of curly hair and a French landmark in your head, you got it wrong.”
invented by
Bertrand Meyer
what does it expect?what does it guarantee?what does it maintain?
a better contract
> prerequisites> postconditions> invariants
dbc tenets
example
stack
> Push(T t)> T Pop()> T Top()> int Count> IsEmpty
stack
dbc by hand
T Pop(){ return _list.RemoveLast();}
example
precondition
T Pop(){ Debug.Assert(!IsEmpty); return _list.RemoveLast();}
void Push(T t){ _list.Add(t);}
example
postcondition
void Push(T t){ try { _list.Add(t); } finally { Debug.Assert(!IsEmpty); }}
invariant
Count >= 0
limitations
tedious!
limitations
clutters the code!
what is
ms code contracts?
dbc.net
code contracts
> rewriter> verifier
rewriter
injects runtime checks
T Pop(){ return _list.RemoveLast();}
example
precondition
T Pop(){ Contract.Requires(!IsEmpty); return _list.RemoveLast();}
rewritten toT Pop(){ if (__ContractsRuntime.insideContractEvaluation <= 4) { try { __ContractsRuntime.insideContractEvaluation++; __ContractsRuntime.Requires(!this.IsEmpty, null, "!IsEmpty"); } finally { __ContractsRuntime.insideContractEvaluation--; } } return this._list.RemoveLast<T>();}
void Push(T t){ _list.Add(t);}
example
postcondition
void Push(T t){ Contract.Ensures(!IsEmpty); _list.Add(t);}
rewritten to
void Push(T t){ this._list.Add(t); if (__ContractsRuntime.insideContractEvaluation <= 4) { try { __ContractsRuntime.insideContractEvaluation++; __ContractsRuntime.Ensures(!this.IsEmpty, null, "!IsEmpty"); } finally { __ContractsRuntime.insideContractEvaluation--; } }}
invariant
[ContractInvariantMethod]private void Invariant(){ Contract.Invariant(Count >= 0);}
verifier
performs static checks
verifier
vs >= premium
verifier
so far
so good
T Pop(){ Contract.Requires(!IsEmpty); Contract.Ensures(Count < Contract.OldValue(Count)); Contract.Ensures(Contract.Result<T>() .Equals(Contract.OldValue(Top()))); return _list.RemoveLast();}
a stricter contract
critique
> ugly syntax> in method body> interface hack
yuck.
what is
spec#?
precondition
T Pop() requires !IsEmpty;{ return _list.RemoveLast();}
postcondition
void Push(T t) ensures !IsEmpty;{ _list.Add(t);}
T Pop() requires !IsEmpty; ensures Count > old(Count); ensures result == old(Top()); { return _list.RemoveLast();}
a stricter contract
much better!
syntax helps
lesson
conclusion
design by contract?
yay!
ms code contracts?
meh.
spec#?
yay!