90 likes | 257 Views
OOSC –Contracts. Design By Contract. A powerful technique for writing reliable software. Specifying the software purpose with the implementation. Key elements: Invariant Preconditions Postconditions. Design By Contract.
E N D
Design By Contract • A powerful technique for writing reliable software. • Specifying the software purpose with the implementation. • Key elements: • Invariant • Preconditions • Postconditions
Design By Contract • Precondition – The constraints under which the routine will function properly. • Postconditions – The state of the class after the routine execution • The Contract: If you call routine R() with the preconditions satisfied, R() will return satisfying the postconditions. • Invariant – Always holds
Invariant • Invariant - @inv • May access all class members or its direct/indirect bases, including private members • Preferable in the class comment
Precondition - @pre May reference class members and arguments Multiple @pre markers are conjugated (AND) Postconditions - @post Use $prev(expression) to access the value at the method entry. Use $ret to denote method’s return value Multiple @post markers are conjugated (AND) Preconditions and Postconditions
Example Precondition /** * @pre !isEmpty() * @post (top == $prev(top- 1)) * @post $ret == elems[top] * @post !isFull */ public synchronized Object pop() { return elems[--top]; } Postconditions
General • Order has no meaning • Recursion – as expected, on every call • Inner classes can access outer classes’ members • Anonymous classes – specify invariant in one of its methods
Union-Find http://www.cs.unm.edu/~rlpm/499/uf.html