04-design-by-contract

advertisement
COSC3311 – Software Design
Quality Software –
Design by Contract
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
0
The waterfall model of the lifecycle
FEASIBILITY STUDY
REQUIREMENTS
ANALYSIS
SPECIFICATION
GLOBAL DESIGN
DETAILED DESIGN
IMPLEMENTATION
VALIDATION &
VERIFICATION
DISTRIBUTION
PROJECT PROGRESS
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
1
The waterfall model of the lifecycle
FEASIBILITY STUDY
REQUIREMENTS
ANALYSIS
DESIGN AND
IMPLEMENTATION
SPECIFICATION
GLOBAL DESIGN
DETAILED DESIGN
IMPLEMENTATION
VALIDATION &
VERIFICATION
DISTRIBUTION
PROJECT TIME
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
2
Problems with the waterfall
 Late appearance of actual code.
 Lack of support for requirements change — and
more generally for extendibility and reusability.
 Lack of support for the maintenance activity (70%
of software costs?).
 Division of labor hampering Total Quality
Management.
 Impedance mismatches.
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
3
Impedance mismatches
As Management requested it.
As Programming developed it.
As the Project Leader defined it.
As Operations installed it.
As Systems designed it.
What the user wanted.
(Pre-1970 cartoon; origin unknown)
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
4
Seamless development
Specification
TRANSACTION, PLANE, CUSTOMER, …
Example classes
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
5
Seamless development
Specification
Design
TRANSACTION, PLANE, CUSTOMER, …
STATE, USER_COMMAND, …
Example classes
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
6
Seamless development
Specification
Design
Implementation
TRANSACTION, PLANE, CUSTOMER, …
STATE, USER, …
HASH_TABLE, LINKED_LIST…
Example classes
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
7
Seamless development
Specification
Design
Implementation
V&V
TRANSACTION, PLANE, CUSTOMER, …
STATE, USER, …
HASH_TABLE, LINKED_LIST…
TEST_DRIVER, …
Example classes
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
8
Seamless development
Specification
Design
Implementation
V&V
TRANSACTION, PLANE, CUSTOMER, …
STATE, USER, …
HASH_TABLE, LINKED_LIST…
TEST_DRIVER, …
Generalization
Example classes
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
9
The goal: Software quality







REUSABILITY
EXTENDIBILITY
RELIABILITY (Correctness + Robustness)
PORTABILITY
EFFICIENCY
INTEGRITY
…
SPECIFICATION
Correctness
Robustness
 Correctness:
o The ability of a software system to perform according to
specification, in cases defined by the specification.
 Robustness:
o The ability of a software system to react in a reasonable
manner to cases not covered by the specification.
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
10
Thinking Quality
 Information Hiding
 Design by Contract
 Test Driven Design
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
11
Information hiding
Public part
Secret part
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
12
The Information Hiding Principle
 The designer of every module must select a subset
of the module’s properties (public features) as the
official information about the module, to be made
available to authors of client modules.
 Which properties of a module should be public,
and which ones secret?
o As a general guideline, the public part should include
the specification of the module’s functionality;
o anything that relates to the implementation of that
functionality should be kept secret
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
13
Application to information hiding
Public features, comments and
contracts
Secret part:
•Choice of representation
• Implementation of public
features
•Private features
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
14
Design by Contract
 A discipline of
o analysis,
o design,
o Implementation
 Use a consistent notation throughout
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
15
A human contract
Delivery service
Client
Supplier
OBLIGATIONS
(Satisfy precondition:)
Bring package before
4 p.m.; pay fee.
(Satisfy postcondition:)
Deliver package by
10 a.m. next day.
Department of Computer Science, York University
BENEFITS
(From postcondition:)
Get package delivered
by 10 a.m. next day.
(From precondition:)
Not required to do
anything if package
delivered after 4 p.m.,
or fee not paid.
Object Oriented Software Construction
2016-03-22 3:39 PM
16
Properties of contracts
 A contract:
o
o
o
o
Binds two parties (or more): supplier, client.
Is explicit (written).
Specifies mutual obligations and benefits.
Usually maps obligation for one of the parties into
benefit for the other, and conversely.
o Has no hidden clauses: obligations are those
specified.
o Often relies, implicitly or explicitly, on general rules
applicable to all contracts (laws, regulations,
standard practices).
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
17
Contracts for analysis
deferred class PLANE
inherit
AIRCRAFT
feature
start_take_off
require
deferred
ensure
end
Precondition
-- Initiate take-off procedures.
controls.passed
assigned_runway.clear
-- i.e. specified only.
assigned_runway.owner = Current
moving
start_landing, increase_altitude, decrease_altitude, moving,
altitude, speed, time_since_take_off
-- not implemented.
Postcondition
... [Other features] ...
Class invariant
invariant
(time_since_take_off <= 20) implies (assigned_runway.owner = Current)
moving = (speed > 10)
end
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
18
Contracts for analysis (cont’d)
start_take_off
Client
Supplier
OBLIGATIONS
BENEFITS
(Satisfy precondition)
Make sure that the
controls are passed
and the assigned
runway is clear .
(From postcondition)
Becomes the owner of
the runway and plane is
moving.
(Satisfy postcondition)
Assign the runway to
the plane and make it
start moving.
(From precondition) Don’t
have to deal with the
issues e.g. controls
are failing or runway is
not clear.
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
19
A contract Example (from EiffelBase)
extend (new: G; key: H)
-- Assuming there is no item of key key,
-- insert new with key; set inserted.
require
key_not_present: not has (key)
ensure
insertion_done: item (key) = new
key_present: has (key)
inserted: inserted
one_more: count = old count + 1
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
20
The class invariant
 Consistency constraint applicable to all instances
of a class.
 Must be satisfied:
o After creation.
o After execution of any feature by any client.
(Qualified calls only: a.f (...))
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
21
Invariants and business rules
 Invariants are absolute consistency conditions.
 They can serve to represent business rules if
knowledge is to be built into the software.
 Form 1
invariant
not_under_minimum: balance >= Minimum_balance
 Form 2
invariant
not_under_minimum_if_normal:
normal_state implies
(balance >= Minimum_balance)
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
22
Correctness in software
Basic notation: (P, Q: assertions, i.e. properties of
the state of the computation. A: instructions).
{P} A {Q}
 “Hoare triple”
 What this means (total correctness):
o Any execution of A started in a state satisfying P will
terminate in a state satisfying Q.
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
23
Concept of State
• Each state is a combination of run-time instance values
for all the class attributes
• Expressed as a tuple of size corresponding to the
number of class attributes
a, b: BOOLEAN 
 <T, T>, <F, T>, <T, F>, <F, F>
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
24
The correctness of a class
create a.make (…)
S1
a.f (…)
 For every creation procedure cp:
S2
{precp} docp {postcp and INV}
a.g (…)
 For every exported routine r:
S3
{INV and prer} dor {postr and INV}
 The worst possible erroneous run-time situation
in object-oriented software development:
o Producing an object that does not satisfy
the invariant of its own class.
Department of Computer Science, York University
Object Oriented Software Construction
a.f (…)
S4
2016-03-22 3:39 PM
25
DbC: Run-time Monitor
{ invariant & P } A { Q & invariant }
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
26
DbC: Run-time Monitor
{ invariant & P } A { Q & invariant }
Department of Computer Science, York University
DbC: Run-time Monitor
{ invariant & P } A { Q & invariant }
Department of Computer Science, York University
DbC: Run-time Monitor
{ invariant & P } A { Q & invariant }
Department of Computer Science, York University
DbC: Run-time Monitor
{ invariant & P } A { Q & invariant }
Department of Computer Science, York University
DbC: Run-time Monitor
{ invariant & P } A { Q & invariant }
Department of Computer Science, York University
DbC: Run-time Monitor
{ invariant & P } A { Q & invariant }
Department of Computer Science, York University
DbC: Run-time Monitor
{ invariant & P } A { Q & invariant }
Department of Computer Science, York University
DbC: Run-time Monitor - Satisfaction
{ invariant & P } A { Q & invariant }
Department of Computer Science, York University
DbC: Run-time Monitor: Weakness
{ invariant & P } A { Q & invariant }
Department of Computer Science, York University
DbC: Run-time Monitor - Weakness
{ invariant & P } A { Q & invariant }
Department of Computer Science, York University
Hoare triples: a simple example
{n > 5} n := n + 9 {n > 13}
 Most interesting properties:
o Strongest postcondition (from given precondition).
o Weakest precondition (from given postcondition).
 “P is stronger than or equal to Q” means:
P implies Q
 An assertion A is stronger than B if A specifies a
property more precisely than B, e.g.,
“party_start_time = 10pm” is stronger than
“party_start_time = evening”
 QUIZ: What is the strongest possible assertion?
The weakest?
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
37
Weak and Strong Assertions
 Suppose we want to describe (specify) this set of
integers:
o { 2 4 8 16 32 ... }
 An assertion can be used to describe integers in a
set
o 1
{
o 2
{
o 3
{
o 4
{
– a set of all integers
Weaker
i: INTEGER • i }
– a set of even integers
i: INTEGER • even (i) }
– a set of powers of two
i: INTEGER • 2 ** i }
– set of powers of two with positive exponent
Stronger
i: INTEGER | i > 0 • 2 ** i }
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
38
Weak and Strong Assertions – 2
 The stronger the assertion the closer the
description comes to specifying the actual set
 In general
o Weak assertions describe bigger sets than strong
assertions
 In programming
o The weaker the assertion the more cases that must
be handled
For precondition – more input states
For postcondition – more output states
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
39
Software correctness
 Consider
{P} A {Q}
 Take this as a job ad in the classifieds.
 Should a lazy employment candidate hope for a
weak or strong P? What about Q?
 Two special offers:
o 1.
o 2.
{False} A {...}
{...} A {True}
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
40
A contract violation is not a special case
 For special cases (e.g. “if the sum is negative,
report an error...”)
use standard control structures (e.g. if ... then ...
else...).
 A run-time assertion violation is something else:
the manifestation of
A DEFECT (“BUG”)
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
41
Contracts and quality assurance
 Precondition violation: Bug in the client.
 Postcondition violation: Bug in the supplier.
 Invariant violation: Bug in the supplier.
{P} A {Q}
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
42
So, is DbC like “assert” in Java 1.4?
 Design by Contract goes further:
o “Assert” does not provide a contract.
o Clients cannot see asserts as part of the interface.
o Asserts do not have associated semantic
specifications.
o Not explicit whether an assert represents a
precondition, post-conditions or invariant.
o Asserts do not support inheritance.
o Asserts do not yield automatic documentation.
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
43
Some benefits: technical
 Development process becomes more focused.
Writing to spec.
 Sound basis for writing reusable software.
 Exception handling guided by precise definition of
“normal” and “abnormal” cases.
 Interface documentation always up-to-date, can
be trusted.
 Documentation generated automatically.
 Faults occur close to their cause. Found faster and
more easily.
 Guide for black-box test case generation.
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
44
Export rule for preconditions
 In
feature {A, B, C}
r (…)
require
some_property
 some_property must be exported (at least) to A, B
and C!
 No such requirement for postconditions and
invariants.
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
45
The contract language
 Language of boolean expressions (plus old):
o No quantifiers,  or , but we can use agents instead.
o Function calls permitted (e.g. in a STACK class):
put (x: G)
remove (x: G)
-- Push x on top of stack.
require
-- Pop top of stack.
require
not is_full
do
not is_empty
do
…
ensure
…
ensure
not is_empty
end
Department of Computer Science, York University
not is_full
end
Object Oriented Software Construction
2016-03-22 3:39 PM
46
Command/Query separation principle
 In assertions, use only side-effect-free functions.
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
47
Precondition design
 The client must guarantee the precondition before the call.
 This does not necessarily mean testing for the precondition.
 Scheme 1 (testing):
if not my_stack.is_full then
my_stack.put (some_element)
end
 Scheme 2 (guaranteeing without testing):
my_stack.remove
...
my_stack.put (some_element)
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
48
Not defensive programming
 For every consistency condition that is required to
perform a certain operation:
o Assign responsibility for the condition to one of the
contract’s two parties (supplier, client).
o Stick to this decision: do not duplicate responsibility.
 Simplifies software and improves global reliability.
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
49
How strong should a precondition be?
 Two opposite styles:
o Tolerant: weak preconditions (including the weakest,
True: no precondition).
o Demanding: strong preconditions, requiring the client to
make sure all logically necessary conditions are satisfied
before each call.
 Partly a matter of taste.
 But: demanding style leads to a better distribution of roles,
provided the precondition is:
o Justifiable in terms of the specification only.
o Documented (through the short form).
o Reasonable!
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
50
A demanding style
sqrt (x, epsilon: REAL): REAL
-- Square root of x, precision epsilon
-- Same version as before
require
x >= 0
epsilon >= 0
do
...
ensure
abs (Result ^ 2 – x) <= 2 * epsilon * Result
end
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
51
A tolerant style
sqrt (x, epsilon: REAL): REAL
NO INPUT
TOO
BIG OR
-- Square root of x, precision epsilon
TOO SMALL!
require
True
do
if x < 0 then
… Do something about it (?) …
else
… normal square root computation …
computed := True
end
ensure
computed implies
abs (Result ^ 2 – x) <= 2 * epsilon * Result
end
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
52
Contrasting styles
put (x: G)
-- Push x on top of stack.
require
not is_full
do
....
end
tolerant_put (x: G)
-- Push x if possible, otherwise set impossible to
-- True.
do
if not is_full then
put (x)
else
impossible := True
end
end
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
53
Methodological notes
 Contracts are not input checking tests...
 ... but they can be used to help weed out
undesirable input.
 Filter modules:
Preconditions here only
External
objects
Department of Computer Science, York University
Input and
validation
modules
Processing
modules
Object Oriented Software Construction
2016-03-22 3:39 PM
54
The imperative and the applicative
do
ensure
balance := balance - sum
balance = old balance - sum
PRESCRIPTIVE
DESCRIPTIVE
How?
What?
Operational
Denotational
Implementation
Specification
Command
Query
Instruction
Expression
Imperative
Applicative
Department of Computer Science, York University
Object Oriented Software Construction
2016-03-22 3:39 PM
55
Download