Upload
elias-halter
View
216
Download
0
Tags:
Embed Size (px)
Citation preview
ceg860(Prasad) L10DC 1
Design by Contract
Invariants
Pre-post conditions : Rights and Obligations
Exceptions : Contract Violations
ceg860(Prasad) L10DC 2
Correctness• Implementation is correctcorrect relative to a
specification.{ P } S { Q }
• Precondition binds the client. • It is an obligation for the client and a benefit for the
supplier.
• Postcondition binds the supplier (routine).• It is an obligation for the supplier and a benefit for
the client.
Non-Redundancy PrincipleNon-Redundancy Principle
ceg860(Prasad) L10DC 3
Spec vs Impl
• Spec:pre: x=0 /\ y=3
post: x=3 /\ y=0
• Implementationsx := 3; y := 0
x :=x+y; y:=x*y
t=x; x=y; y=t;
• Spec?
pre: true
post: x*x = 2
• Spec
pre: > 0
post: x*x -2 <
ceg860(Prasad) L10DC 4
Insertion Sort(define (insertion-sort lon) (if (null? lon) () (insert (car lon) (insertion-sort (cdr lon)) ) ))
// car = first/head, cdr = rest/tail
(insertion-sort '(2 3 1 4 7 5) )= (1 2 3 4 5 7)
ceg860(Prasad) L10DC 5
(define (insert n lon) (cond ((null? lon) (list n)) ((> n (car lon)) (cons (car lon) (insert n (cdr lon)) ) ) (else (cons n lon))))
• Precondition : lon is ordered.• Postcondition : (insert n lon) is ordered.
ceg860(Prasad) L10DC 6
Assertions
In theory, assertions are first-order logic formulae.
In a programming language, assertions are computable boolean expressions that can contain program variables, arithmetic/boolean operations, and possibly, user-defined functions.
ceg860(Prasad) L10DC 7
(cont’d)
In Eiffel, the expression OLD attr in
postcondition denotes the value of the
attribute attr on routine entry.
In general, the preconditions must not use
features hidden from the clients. However,
the postconditions can use any feature, even
though only clauses without hidden features
are directly usable by the client.
ceg860(Prasad) L10DC 8
Algebraic Specification Example
ceg860(Prasad) L10DC 9
ADT GStack
create: -> GStack
push: Gstack x G -> GStack
pop: Gstack -> GStack
top: GStack -> G
empty: Gstack -> boolean
constructors: create, pushobservers: top, emptynon-constructors: pop
ceg860(Prasad) L10DC 10
Forall s GStack, x G:
pop(push(s,x)) = s
top(push(s,x)) = x
empty(create()) = trueempty(push(s,x)) = false
Preconditions:
pop(s) requires s =/= create()top(s) requires s =/= create()
ceg860(Prasad) L10DC 11
ADT (Bounded) GStack
create: int -> GStackpush: Gstack x G -> GStackpop: Gstack -> GStacktop: GStack -> Gempty: Gstack -> booleanfull: Gstack -> boolean
constructors: create, pushobservers: top, empty, fullnon-constructors: pop
ceg860(Prasad) L10DC 12
• Auxiliary functions:
Forall s Gstack Terms:
n int, x G: n>0 :
count(create(n)) = 0count(push(s,x)) = 1 + count(s)
capacity(create(n)) = ncapacity(push(s,x)) = capacity(s)
ceg860(Prasad) L10DC 13
Preconditions:
Forall s Gstack Terms,
n int, x G: n>0 :
pop(s) requires s =/= create(n)
top(s) requires s =/= create(n)
push(s,x)requires capacity(s)
>= count(s) + 1
ceg860(Prasad) L10DC 14
Forall s GStack, n int, x G: n>0 :
pop(push(s,x)) = s
top(push(s,x)) = x
empty(create(n)) = true
empty(push(s,x)) = false
full(s) = (capacity(s) = count(s))
ceg860(Prasad) L10DC 15
Specifying Class
ceg860(Prasad) L10DC 16
Categories of Operations
• Creators ( …x … • Constructors
• Queries (…x T x … …)• Observers
• Commands (…x T x … • Constructors, Non-constructors
ceg860(Prasad) L10DC 17
class IntStack { private int capacity ;
private int count; public IntStack(int c) { ...
// require: c >=0 // ensure: capacity = c // ensure: empty()
// ensure: count = 0 } public void push(int e) { ...
// require: not full()// ensure: top() = e// ensure: not empty()
// ensure: count = old count + 1 }
ceg860(Prasad) L10DC 18
public void pop() {... // require: not empty() // ensure: not full() // ensure: count = old count - 1
} public int top() {...
// require: not empty() }
public boolean empty() {...} public boolean full() {...}
// class invariants: // empty() = (count = 0)
// full() = (count = capacity) // pop(push(e)) = identity-map}
ceg860(Prasad) L10DC 19
Class Invariant
• A class invariantclass invariant for C is a set of assertions that every instance of C must satisfy at all “stable” times. That is, immediately after its creation and before/after a public method call (by a client).
• The class invariant relates attributes and/or functions.
• E.g., 0 <= count <= capacity• E.g., (count > 0) => (s[count] = top())
ceg860(Prasad) L10DC 20
Role of Class Invariants in Software Engineering
• InvariantsInvariants not only apply to the routines actually written in the class, but also to any routines added later.
• Correctness of a method Correctness of a method methmeth {P and Inv} meth_body {Q and Inv}
• Role of constructor definitionsRole of constructor definitions If default initialization of the fields violates
class invariant, an explicit constructor is needed.
ceg860(Prasad) L10DC 21
From ADT specs to Pre-Post Conditions
• A precondition for a specs’ functionfunction
reappears as a precondition for the
corresponding routineroutine.
• Axioms involving a commandcommand
(possibly with queriesqueries) reappear as
postconditions of the corresponding
procedureprocedure.
ceg860(Prasad) L10DC 22
(cont’d) • Axioms involving only queriesqueries
reappear as postconditions of the corresponding functionsfunctions or as clausesclauses of the class invariant.
• Axioms involving a creatorcreator reappear in the postcondition of the corresponding constructor constructor procedureprocedure.
ceg860(Prasad) L10DC 23
Introducing Representationclass IntStack {
private int[] s ; ... public IntStack(int c) { ... // ensure: s =/= null }; public void push(int e) { ... // ensure: s[count] = e
// ensure: for i in [1..count-1] do // s[i] = old s[i]
}; public void pop() { ...
// ensure: for i in [1..count-1] do // s[i] = old s[i]
}; ... } //--FRAME AXIOMS--//
ceg860(Prasad) L10DC 24
Model-based Spec. and Impl.
• Implementation/Representation invariant Assertion characterizing the set of concrete
objects that are implementations of the abstract objects (cf. class invariant).
• Abstraction function Maps a concrete object (satisfying
representation invariant) to the corresponding abstract object.
• Usually ontoonto but not one-onenot one-one.
ceg860(Prasad) L10DC 25
“Bugs”• A run-time assertion violation is a
manifestation of a bug in the software.• Precondition violation : Bug in the client.• Postcondition violation : Bug in the supplier.
• Error • A wrong decision made during software
development.
• Defect • The property of a software that may cause the system
to depart from its intended behavior.
• Fault• The event of a software departing from its intended
behavior.
ceg860(Prasad) L10DC 26
Failure
• A routine call failsfails if it terminates its execution in a state that does not satisfy the routine’s contract.
• Violates postcondition or class invariant.
• Calls a routine whose precondition is violated.
• Causes an abnormal OS signal such as arithmetic overflow, memory exhaustion, etc.
ceg860(Prasad) L10DC 27
Exception
• An exceptionexception is a run-time event that may cause a routine call to fail.
• Every failure results from an exception, but not every exception results in a failure (if the routine can recover from it).
ceg860(Prasad) L10DC 28
Disciplined Exception Handling• Rescue Clause
– RetryRetry• Attempt to change the conditions that led to the
exception and execute the routine again from the start (possibly, exploring alternatives).
– Software fault tolerance.
{ true } Retry_Body { Inv and Pre }
– FailureFailure• Clean-up the environment (restore the invariant),
terminate the call and report failure to the caller.
{ true } Rescue_Body { Inv }
ceg860(Prasad) L10DC 29
Developer Exceptions
• Exceptions are propagated up the call chain (dynamic).
• A supplier code can define an exception and raise it, to enable context-sensitive handling of the exception by the various clients.– In Java, an exception is a typed packet of
information (object), which is useful in locating and diagnosing faults. Checked exceptions contribute to robustness by forcing the client to process exception explicitly, or propagate it explicitly.