Design by Contract 1 Design by Contract Softw are Engineering - - PDF document

design
SMART_READER_LITE
LIVE PREVIEW

Design by Contract 1 Design by Contract Softw are Engineering - - PDF document

Design by Contract 1 Design by Contract Softw are Engineering Design by Contract Every software element is intended to satisfy a certain goal, for the benefit of other software elements (and ultimately of human users). This goal is the


slide-1
SLIDE 1

1

Design by Contract

1 Softw are Engineering

Design

by

Contract™

Design by Contract

2 Softw are Engineering

Design by Contract

Every software element is intended to satisfy a certain goal, for the benefit of other software elements (and ultimately of human users). This goal is the element’s contract. The contract of any software element should be Explicit. Part of the software element itself.

Design by Contract

3 Softw are Engineering

Design by Contract: applications

Built-in correctness Automatic documentation Self-debugging, self-testing code Get inheritance right Get exceptions right Give managers better control tools

slide-2
SLIDE 2

2

Design by Contract

4 Softw are Engineering

Constructing systems as structured collections of cooperating software elements — suppliers and clients — cooperating on the basis of clear definitions of obligations and benefits These definitions are the contracts Softw are construction: the underlying view

Design by Contract

5 Softw are Engineering

Properties of contracts

A contract: 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 Has no hidden clauses: obligations are those specified Often relies, implicitly or explicitly, on general rules applicable to all contracts (laws, regulations, standard practices)

Design by Contract

6 Softw are Engineering

A human contract

Client Supplier

(Satisfy precondition:) Bring package before 4 p.m.; pay fee. (Satisfy postcondition:) Deliver package by 10 a.m. next day.

OBLIGATIONS

(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.,

  • r fee not paid.

BENEFITS

deliver

slide-3
SLIDE 3

3

Design by Contract

7 Softw are Engineering

EiffelStudio documentation

Produced automatically from class text Available in text, HTML, Postscript, RTF, FrameMaker and many other formats Numerous views, textual and graphical

Design by Contract

8 Softw are Engineering

Contracts for documentation

LINKED_LIST Documentation, generated by EiffelStudio Demo

Design by Contract

9 Softw are Engineering

Contract form: Definition

Simplified form of class text, retaining interface elements

  • nly:

Remove any non-exported (private) feature. For the exported (public) features: Remove body (do clause). Keep header comment if present. Keep contracts: preconditions, postconditions, class invariant. Remove any contract clause that refers to a secret

  • feature. (What’s the problem?)
slide-4
SLIDE 4

4

Design by Contract

10 Softw are Engineering

The different forms of a class

Elements from the class only Elements from the class and it’s ancestors

Text view: text form

All features and contract clauses Only the exported (non secret) elements

Contract view: short form Flat view: flat form Interface view: flat short form

Design by Contract

11 Softw are Engineering

Export rule for preconditions

In some_property must be exported (at least) to A, B and C! No such requirement for postconditions and invariants.

feature { A, B, C} r (… ) is require some_property

Chair of Softw are Engineering

deferred class VAT inherit TANK feature in_valve, out_valve: VALVE fill is

  • - Fill the vat.

require in_valve.open

  • ut_valve.closed

deferred ensure in_valve.closed

  • ut_valve.closed

is_full end empty, is_full, is_empty, gauge, maximum, ... [Other features] ... invariant is_full = (gauge >= 0.97 ∗ maximum) and (gauge <= 1.03 ∗ maximum) end

Contracts for analysis, specification

slide-5
SLIDE 5

5

Design by Contract

13 Softw are Engineering

Contracts for testing and debugging

Contracts express implicit assumptions behind code A bug is a discrepancy between intent and code Contracts state the intent! In EiffelStudio: select compilation option for run-time contract monitoring at level of: Class Cluster System May disable monitoring when releasing software A revolutionary form of quality assurance

Design by Contract

14 Softw are Engineering

Lists in EiffelBase

“Iowa"

Cursor

item index count 1 forth back finish start after before

Design by Contract

15 Softw are Engineering

Trying to insert too far right

Cursor

(Already past last element!)

count 1 after "Iowa"

slide-6
SLIDE 6

6

Design by Contract

16 Softw are Engineering

A command and its contract

Precondition Postcondition

Design by Contract

17 Softw are Engineering

Moving the cursor forw ard

"Iowa"

Cursor

index count 1 forth after before

Design by Contract

18 Softw are Engineering

Tw o queries, and command “forth″

slide-7
SLIDE 7

7

Design by Contract

19 Softw are Engineering

Where the cursor may go

count+1

Valid cursor positions

item count 1 after before

Design by Contract

20 Softw are Engineering

From the invariant of class LIST

Valid cursor positions

Design by Contract

21 Softw are Engineering

Contract monitoring

A contract violation always signals a bug: Precondition violation: bug in client Postcondition violation: bug in routine

slide-8
SLIDE 8

8

Design by Contract

22 Softw are Engineering

Contracts and inheritance

Issues: what happens, under inheritance, to Class invariants? Routine preconditions and postconditions?

Design by Contract

23 Softw are Engineering

Invariants

Invariant Inheritance rule: The invariant of a class automatically includes the invariant clauses from all its parents, “and”-ed. Accumulated result visible in flat and interface forms.

Design by Contract

24 Softw are Engineering

Contracts and inheritance

r is require

γ

ensure

δ

r is require

α

ensure

β

a1: A a1.r (…) …

Correct call in C: if a1.α then a1.r (...)

  • - Here a1.β hold

end

r ++

C A D B

Client Inheritance

++ Redefinition

slide-9
SLIDE 9

9

Design by Contract

25 Softw are Engineering

Assertion redeclaration rule

When redeclaring a routine, we may only: Keep or weaken the precondition Keep or strengthen the postcondition

Design by Contract

26 Softw are Engineering

A simple language rule does the trick! Redefined version may have nothing (assertions kept by default), or require else new_pre ensure then new_post Resulting assertions are:

  • riginal_precondition or new_pre
  • riginal_postcondition and new_post

Assertion redeclaration rule in Eiffel

Design by Contract

27 Softw are Engineering

Contracts as a management tool

High-level view of modules for the manager: Follow what’s going on without reading the code Enforce strict rules of cooperation between units of the system Control outsourcing

slide-10
SLIDE 10

10

Design by Contract

28 Softw are Engineering

Checking input: filter modules

Contracts are not input checking tests... ... but they can help weed out undesirable input

External

  • bjects

Input & validation modules Processing modules Preconditions here only No preconditions! Postconditions

⇒ ⇒

Design by Contract

29 Softw are Engineering

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)

Design by Contract

30 Softw are Engineering

Another example

sqrt (x, epsilon: REAL): REAL is

  • - Square root of x, precision epsilon

require x >= 0 epsilon >= 0 do ... ensure abs (Result ^ 2 – x) <= 2 * epsilon * Result end

slide-11
SLIDE 11

11

Design by Contract

31 Softw are Engineering

The contract

Client Supplier

(Satisfy precondition:) Provide non-negative value and precision that is not too small. (Satisfy postcondition:) Produce square root within requested precision.

OBLIGATIONS

(From postcondition:) Get square root within requested precision. (From precondition:) Simpler processing thanks to assumptions

  • n value and

precision.

BENEFITS

sqrt

Design by Contract

32 Softw are Engineering

Not defensive programming

It is not acceptable to have a routine of the form

sqrt (x, epsilon: REAL): REAL is

  • - Square root of x, precision epsilon

require x >= 0 epsilon >= 0 do if x < 0 then … Do something about it (?) … else … normal square root computation … end ensure abs (Result ^ 2 – x) <= 2 * epsilon * Result end

Design by Contract

33 Softw are Engineering

Not defensive programming

For every consistency condition that is required to perform a certain operation: Assign responsibility for the condition to one of the contract’s two parties (supplier, client). Stick to this decision: do not duplicate responsibility. Simplifies software and improves global reliability.

slide-12
SLIDE 12

12

Design by Contract

34 Softw are Engineering

Interpreters

class BYTECODE_PROGRAM feature verified: BOOLEAN trustful_execute (program: BYTECODE) is require

  • k: verified

do ... end distrustful_execute (program: BYTECODE) is do verify if verified then trustful_execute (program) end end verify is do ... end end

Design by Contract

35 Softw are Engineering

How strong should a precondition be?

Two opposite styles: Tolerant: weak preconditions (including the weakest, True: no precondition). 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: Justifiable in terms of the specification only. Documented (through the short form). Reasonable!

Design by Contract

36 Softw are Engineering

A demanding style

sqrt (x, epsilon: REAL): REAL is

  • - 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

slide-13
SLIDE 13

13

Design by Contract

37 Softw are Engineering

sqrt (x, epsilon: REAL): REAL is

  • - Square root of x, precision epsilon

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

A tolerant style

NO INPUT TOO BIG OR TOO SMALL!

Design by Contract

38 Softw are Engineering

Contrasting styles

put (x: G) is

  • - Push x on top of stack.

require not is_full do .... end tolerant_put (x: G) is

  • - Push x if possible, otherwise set impossible to
  • - True.

do if not is_full then put (x) else impossible := True end end

Design by Contract

39 Softw are Engineering

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)

slide-14
SLIDE 14

14

Design by Contract

40 Softw are Engineering

Pow er of the assertion language

Assertion language: Not first-order predicate calculus But powerful through:

Function calls

Even allows to express:

Loop properties

Design by Contract

41 Softw are Engineering

Loop trouble

Loops can be hard to get right: “Off-by-one” Infinite loops Improper handling of borderline cases For example: binary search feature

Design by Contract

42 Softw are Engineering

The answ er: loop contracts

Use of loop variants and invariants. A loop is a way to compute a certain result by successive approximations. (e.g. computing the maximum value of an array of integers)

slide-15
SLIDE 15

15

Design by Contract

43 Softw are Engineering

Computing the max of an array

highest (sl: LIST [STRING]): STRING is

  • - Greatest element of sl

require sl /= Void not sl.is_empty do from sl.start ; Result := "" until sl.after loop Result := greater (Result, sl.item) sl.forth end end

Design by Contract

44 Softw are Engineering

Loop as approximation strategy

s1 s2 si sn

Result = s1 Result = Max (s1, s2) Result = Max (s1, s2, ..., si) Result = Max (s1, s2, ..., si , ..., sn)

Design by Contract

45 Softw are Engineering

The loop invariant

from sl.start ; Result := "“ invariant sl.index >= 1 sl.index <= sl.count + 1

  • - Result is greatest of elements so far

until sl.after loop Result := greater (Result, sl.item) sl.forth end

slide-16
SLIDE 16

16

Design by Contract

46 Softw are Engineering

Loop invariant

(Do not confuse with class invariant) Property that is: Satisfied after initialization (from clause) Preserved by every loop iteration (loop clause) when executed with the exit condition (until clause) not satisfied

Design by Contract

47 Softw are Engineering

The loop invariant

from sl.start ; Result := "" invariant sl.index >= 1 sl.index <= sl.count + 1

  • - Result is greatest of elements so far

until sl.after loop Result := greater (Result, sl.item) sl.forth end

Design by Contract

48 Softw are Engineering

The loop invariant (better)

from sl.start ; Result := "" invariant sl.index >= 1 sl.index <= sl.count + 1

  • - If there are any previous elements, Result is the greatest

until sl.after loop Result := greater (Result, sl.item) sl.forth end

slide-17
SLIDE 17

17

Design by Contract

49 Softw are Engineering

The effect of the loop

from sl.start ; Result := "" invariant sl.index >= 1 sl.index <= sl.count + 1

  • - Result is greatest of elements so far

until sl.after loop Result := greater (Result, sl.item) sl.forth end

Invariant satisfied after initialization Invariant satisfied after each iteration Exit condition satisfied at end At end: invariant and exit condition

  • All elements visited (sl.after )
  • Result is highest of their names

Design by Contract

50 Softw are Engineering

Loop semantics rule

The effect of a loop is the combination of: Its invariant Its exit condition

Design by Contract

51 Softw are Engineering

How do w e know the loop terminates?

from sl.start ; Result := "“ invariant sl.index >= 1 sl.index <= sl.count + 1

  • - If there are any previous elements, Result is the greatest

until sl.after loop Result := greater (Result, sl.item) sl.forth end

slide-18
SLIDE 18

18

Design by Contract

52 Softw are Engineering

Loop variant

Integer expression that must: Be non-negative when after initialization (from) Decrease (i.e. by at least one), while remaining non- negative, for every iteration of the body (loop) executed with exit condition not satisfied

Design by Contract

53 Softw are Engineering

The variant for our loop

from sl.start ; Result := "“ variant sl.count − sl.index + 1 invariant sl.index >= 1 sl.index <= sl.count + 1

  • - If there are any previous elements, Result is the greatest

until sl.after loop Result := greater (Result, sl.item) sl.forth end

Design by Contract

54 Softw are Engineering

Another contract construct

Check instruction: ensure that a property is True at a certain point of the routine execution. E.g. Tolerant style example: Adding a check clause for readability.

slide-19
SLIDE 19

19

Design by Contract

55 Softw are Engineering

Precondition design

Scheme 2 (guaranteeing without testing): my_stack.remove check my_stack_not_full: not my_stack.is_full end my_stack.put (some_element)