Designby
Contract
Specifications• Correctness formula (Hoare triple)
{P} A {Q}– A is some operation (for example, a routine body)– P and Q are predicates– P is called precondition– Q is called postcondition
• Meaning of a correctness formula:“Any execution of A, starting in a state where P holds, will terminate in a state where Q holds”
• Example:{ x >= 9} x:=x+5 {x>=13}
Eiffel Exampleclass STACK[G]
count: INTEGER-- Number of stack elements
item: G-- Top element
empty: BOOLEAN is-- Is stack empty?do … end
full: BOOLEAN is-- Is stack representation full?do ... end
…
Eiffel Example (2)class STACK[G]…put (x: G) is
-- Add x on toprequirenot_full: not fulldo ...ensure
not_empty: not emptyadded_to_top: item = xone_more_item: count = old count + 1
end…
Invariant• A set of assertions that every instance of the class willsatisfy:
– immediately following the creation– before and after any “remote” call to the routine of the class
• Class invariant is an object “state” restriction
• Correctness formula (revisited){P and INVARIANT} A {Q and INVARIANT}
class STACK[G]…invariant
non_negative_count: count >= 0end
Loop Assertions• Loop invariant
the list of assertions, which will be validated before each loop cycle
• Loop variant– designed to protect against infinite calculations– an integer expression, which is checked before each loop cycle– if one of the following is violated, the loop assertion is violated:
loop variant has to decrease properly each loop cycle loop variant has to remain nonnegative
Find the smallest element in an arrayfrom
i := a.lowers := a.item(i)
invariant -- s is the smallest element in the set – -- {a.item (a.lower), ..., a.item(i)}
variant a.upper – i
until i = a.upper
loop i := i + 1s := s.min(a.item(i))
end
Assertion Redeclaration ruleIn the redeclared version of a routine, it is not permitted to use a require or ensure clause. Instead you may:
• Introduce a new condition with require else, for boolean or with the original precondition.
• Introduce a new condition with ensure then, for boolean and with the original postcondition.
In the absence of such a clause, the original assertions are retained.
Example (1)class A …
foo (x : INTEGER ) isrequire r1do… end
end;
class B inherit A …foo (x : INTEGER ) is
require r2do … end
end;
• The actual requirement is 1 2r r
Example (2)class A …
foo (x : INTEGER ) isdo … ensure e1 end
end;
class B inherit A …foo (x : INTEGER ) is
do… ensure e2 end
end;• The actual promise is 1 2e e
Invariants Redeclaration ruleThe invariant property of class is the boolean and of
the assertions appearing in its invariant clause and of the invariant properties of its parents if any.
class A …invariant i1end;
class B inherit A …invariant i2end;
The actual invariant is 1 2i i