1 Introduction to: Design by Contract Fall 2005 OOPD John Anthony.

Slides:



Advertisements
Similar presentations
Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Prof. Dr. Bertrand Meyer Exercise Session 5.
Advertisements

Design by Contract.
Building Bug-Free O-O Software: An Introduction to Design By Contract A presentation about Design By Contract and the Eiffel software development tool.
1. Define the concept of assertions. 1 Explain the use of assertions. 2 Create Java program using assertions. 3 Run Java program using assertions. 4 2.
Karlstad University Computer Science Design Contracts and Error Management Design Contracts and Errors A Software Development Strategy Eivind J. Nordby.
Practice Session 5 Java: Packages Collection Classes Iterators Generics Design by Contract Test Driven Development JUnit.
Semantics Static semantics Dynamic semantics attribute grammars
Addressing the Challenges of Current Software. Questions to Address Why? What? Where? How?
Chair of Software Engineering OOSC - Summer Semester Object-Oriented Software Construction Bertrand Meyer Lecture 3: Abstract Data Types.
Design by Contract. Design by contract is the process of developing software based on the notion of contracts between objects, which are expressed as.
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
1 Design by Contract Building Reliable Software. 2 Software Correctness Correctness is a relative notion  A program is correct with respect to its specification.
Design by Contract. Specifications Correctness formula (Hoare triple) {P} A {Q} – A is some operation (for example, a routine body) – P and Q are predicates.
Software Testing and Quality Assurance
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Prof. Dr. Bertrand Meyer Lecture 4: The Interface of a Class.
Chair of Software Engineering OOSC - Lecture 4 1 Object-Oriented Software Construction Bertrand Meyer.
1 Lecture 24 Abstract Data Types (ADT) –I Overview  What is an Abstract Data type?  What is Stack ADT?  Stack ADT Specifications  Array Implementation.
Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Prof. Dr. Bertrand Meyer Lecture 4: The Interface of a Class.
Karlstad University Computer Science Design Contracts and Error Management Design Contracts and Errors A Software Development Strategy (anpassad för PUMA)
Chair of Software Engineering Concurrent Object-Oriented Programming Prof. Dr. Bertrand Meyer Lecture 9: Contracts and Inheritance (based on work with.
Chair of Software Engineering 1 Introduction to Programming Exercise Session Week 9 M. Piccioni 17/18 November 2008.
Eiffel Language and Design by Contract Contract –An agreement between the client and the supplier Characteristics –Expects some benefits and is prepared.
Data Abstraction: The Walls
Adding Contracts to Ada Ehud Lamm Adding Design By Contract to Ada.
1 © Wolfgang Pelz Design by Contract Design by Contract™ Based on material drawn from: Bertrand.
Subclasses and Subtypes CMPS Subclasses and Subtypes A class is a subclass if it has been built using inheritance. ▫ It says nothing about the meaning.
An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 5 : Programming By Contract.
Computer Science 340 Software Design & Testing Design By Contract.
Ranga Rodrigo. Class is central to object oriented programming.
Topic 3 The Stack ADT.
Chapter 3 Introduction to Collections – Stacks Modified
© Bertrand Meyer and Yishai Feldman Notice Some of the material is taken from Object-Oriented Software Construction, 2nd edition, by Bertrand Meyer (Prentice.
Using UML, Patterns, and Java Object-Oriented Software Engineering Chapter 9, Object Design: Specifying Interfaces.
Introduction CS 3358 Data Structures. What is Computer Science? Computer Science is the study of algorithms, including their  Formal and mathematical.
Chapter 7 Stacks. © 2004 Pearson Addison-Wesley. All rights reserved 7-2 The Abstract Data Type: Developing an ADT During the Design of a Solution Specifications.
Introduction CS 3358 Data Structures. What is Computer Science? Computer Science is the study of algorithms, including their  Formal and mathematical.
CSC 480 Software Engineering Design by Contract. Detail Design Road Map Begin with architectural models  Class model: domain classes  Overall state.
Data Abstaraction Chapter 10.
Protocols Software Engineering II Wirfs Brock et al, Designing Object-Oriented Software, Prentice Hall, Mitchell, R., and McKim, Design by Contract,
1 Devon M. Simmonds, Computer Science Department Design by Contract Devon M. Simmonds Computer Science Department University of North Carolina, Wilmington.
ANU COMP2110 Software Design in 2003 Lecture 10Slide 1 COMP2110 Software Design in 2004 Lecture 12 Documenting Detailed Design How to write down detailed.
L13: Design by Contract Definition Reliability Correctness Pre- and post-condition Asserts and Exceptions Weak & Strong Conditions Class invariants Conditions.
SWE 4743 Abstract Data Types Richard Gesick. SWE Abstract Data Types Object-oriented design is based on the theory of abstract data types Domain.
Ceg860 (Prasad)L17IT1 Inheritance Techniques Subcontracting Anchored Types.
Chapter 1 Data Abstraction: The Walls CS Data Structures Mehmet H Gunes Modified from authors’ slides.
1 Assertions. 2 A boolean expression or predicate that evaluates to true or false in every state In a program they express constraints on the state that.
31/01/ Selection If selection construct.
PROGRAMMING PRE- AND POSTCONDITIONS, INVARIANTS AND METHOD CONTRACTS B MODULE 2: SOFTWARE SYSTEMS 13 NOVEMBER 2013.
CSSE501 Object-Oriented Development. Chapter 10: Subclasses and Subtypes  In this chapter we will explore the relationships between the two concepts.
Object-Oriented Design Concepts University of Sunderland.
DBC NOTES. Design By Contract l A contract carries mutual obligations and benefits. l The client should only call a routine when the routine’s pre-condition.
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Object Design More Design Patterns Object Constraint Language Object Design Specifying Interfaces Review Exam 2 CEN 4010 Class 18 – 11/03.
Design by Contract. The Goal Ensure the correctness of our software (correctness) Recover when it is not correct anyway (robustness) Correctness: Assertions.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
© Bertrand Meyer and Yishai Feldman Notice Some of the material is taken from Object-Oriented Software Construction, 2nd edition, by Bertrand Meyer (Prentice.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Sections 3.4 Formal Specification
Class Invariants Class invariants are logical conditions to ensure the correct working of a class. Class invariants must hold true when an object is created,
Design by Contract Jim Fawcett CSE784 – Software Studio
Design by Contract Jim Fawcett CSE784 – Software Studio
COMPUTER 2430 Object Oriented Programming and Data Structures I
Cs212: Data Structures Computer Science Department Lecture 6: Stacks.
Assertions References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 4/25/2019.
Computer Science 340 Software Design & Testing
Contract-Based Programming with/without Ada 2012
Design Contracts and Errors A Software Development Strategy
Presentation transcript:

1 Introduction to: Design by Contract Fall 2005 OOPD John Anthony

2John J. Anthony Object Oriented Programming & Design Design Question You have created a Car class with an operation named addEnging(e : Engine). The rule is that you can only add one engine to the car (adding two is invalid). How would you implement this rule? return a boolean value indicating the success of adding an engine allow the addEngine to be called and then throw an exception if an engine already exists. ask the client to check the state of the Car to determine if it already has an engine 1 AND 3

3John J. Anthony Object Oriented Programming & Design What is a Contract An entity which describes the obligations between 2 or more parties which, when fulfilled, provides certain rights to the parties.

4John J. Anthony Object Oriented Programming & Design More Specifically Assertion Type ObligationRight PreconditionClient Clients must fulfill the precondition as specified by a supplier. Client If obligation met, client has the right to expect the postconditions are true PostconditionSupplier Supplier must provide certain guarantees when service is invoked Supplier Has the right to expect the preconditions are true. Contracts are “specs ‘n’ checks.”

5John J. Anthony Object Oriented Programming & Design Courier Example ClientSupplier ObligationPrecondition Don’t ask for delivery of packages over 5 lbs in weight Postcondition Deliver package within 3 working hours BenefitPostcondition Get package delivered within 3 working hours. Precondition Don’t have to cope with packages over 5 lbs in weight.

6John J. Anthony Object Oriented Programming & Design Example count: INTEGER -- the number of customers the managing object manages id_active(an_id : CUSTOMER_ID) : BOOLEAN -- is there a customer with ‘an_id’ add(a_customer : BASIC_CUSTOMER_DETAILS) -- add ‘a_customer’ to the set of customers being managed name_for(an_id : CUSTOMER_ID): STRING --what is the name of the customer with ‘an_id’ set_name(an_id : CUSTOMER_ID, a_name : STRING) --set the name of the customer with ‘an_id’ to ‘a_name’ CUSTOMER_MANAGER

7John J. Anthony Object Oriented Programming & Design Example id : CUSTOMER_ID name : STRING address : STRING date_of_birth : DATE BASIC_CUSTOMER_DETAILS

8John J. Anthony Object Oriented Programming & Design Example BASIC_CUSTOMER_DETAILS CUSTOMER_MANAGER

9John J. Anthony Object Oriented Programming & Design Some Design Questions How do I make an id active? By adding a customer with that id? How do I make an id active? By adding a customer with that id? If I add a customer whose details match an existing customer’s basic details, what happens? If I add a customer whose details match an existing customer’s basic details, what happens? What do I get if I ask for the name of a customer whose id is not active? What do I get if I ask for the name of a customer whose id is not active? What happens if I set the name for a customer whose id is not active? What happens if I set the name for a customer whose id is not active?

10John J. Anthony Object Oriented Programming & Design Adding a New Customer add(a_customer : BASIC_CUSTOMER_DETAILS) --add ‘a_customer’ to the set of customers require id_not_already_active: not id_active(a_customer.id) ……..ensure count_increased : count = old count + 1 customer_id_now_active : id_active(a_customer.id) precondition: responsibility of client to ensure expression is true postcondition: responsibility of supplier to ensure expressions are true after feature execution assertion: an expression that must evaluate to true

11John J. Anthony Object Oriented Programming & Design Some Answers… How do I make an id active? By adding a customer with that id? How do I make an id active? By adding a customer with that id? Yes Yes If I add a customer whose details match an existing customer’s basic details, what happens? If I add a customer whose details match an existing customer’s basic details, what happens? Not allowed to add a customer whose id equals the id of a customer already owned by the manager. There are no other constrains on other features such as name, address, DOB, etc. Not allowed to add a customer whose id equals the id of a customer already owned by the manager. There are no other constrains on other features such as name, address, DOB, etc.

12John J. Anthony Object Oriented Programming & Design Setting the Name of Customer set_name(an_id : CUSTOMER_ID, a_name : STRING) --set the name of the customer with ‘an_id’ to ‘a_name’ require id_active: id_active(an_id) ……..ensure name_set: name_for(an_id).is_equal(a_name)

13John J. Anthony Object Oriented Programming & Design Asking for the Name of a Customer name_for(an_id : CUSTOMER_ID : STRING --the name of the customer with ‘an_id’ require id_active: id_active(an_id) ……..

14John J. Anthony Object Oriented Programming & Design More Answers… What do I get if I ask for the name of a customer whose id is not active? What do I get if I ask for the name of a customer whose id is not active? It is illegal to ask for the name of a customer whose id is not active. It is illegal to ask for the name of a customer whose id is not active. What happens if I set the name for a customer whose id is not active? What happens if I set the name for a customer whose id is not active? It is illegal to attempt to set the name of a customer whose id is not active. It is illegal to attempt to set the name of a customer whose id is not active.

15John J. Anthony Object Oriented Programming & Design Class Invariants A condition that always resolves to True (more precisely, it is true whenever you can call a feature on the component). invariant count_never_negative: count >= 0

16John J. Anthony Object Oriented Programming & Design Contract Violations What would happen if we (attempt) to add a customer whose id is already active? Stopped in object [0xE96978] Class: CUSTOMER_MANAGER Feature: add Problem: Precondition violated Tag: id_not_already_active Arguments: a_customer: BASIC_CUSTOMER_DETAILS [OXe9697C] Call Stack: CUSTOMER_MANAGER add was called by CUSTOMER_MANAGER_UIF change_customer

17John J. Anthony Object Oriented Programming & Design A Simple Stack count: INTEGER Is_empty : BOOLEAN initialize push (i : INTEGER) pop(out I : INTEGER) STACK

18John J. Anthony Object Oriented Programming & Design Principle 1 Separate commands from queries Queries return a result but do not change the visible properties of the object. Commands might change the object but do not return a result.

19John J. Anthony Object Oriented Programming & Design Principle 1 Let’s write the contract for the push command… push (I : INTEGER) --push ‘i onto the top of the Stack ….ensure top_is_i : i = ????? count: INTEGER Is_empty : BOOLEAN initialize push (i : INTEGER) pop() : INTEGER STACK push (I : INTEGER) --push ‘i onto the top of the Stack ….ensure top_is_i : i = pop

20John J. Anthony Object Oriented Programming & Design push (I : INTEGER) --push ‘i onto the top of the Stack ….ensure top_is_i : i = pop count: INTEGER Is_empty : BOOLEAN initialize push (i : INTEGER) top : INTEGER delete STACK push (I : INTEGER) --push ‘i onto the top of the Stack ….ensure top_is_i : top = i Principle 1

21John J. Anthony Object Oriented Programming & Design Commands vs. Queries features routines procedures attributes functions creationother QUERIES COMMANDS

22John J. Anthony Object Oriented Programming & Design The Revised Stack count: INTEGER Is_empty : BOOLEAN initialize push (i : INTEGER) top : INTEGER delete STACK > count: INTEGER --the number of items on the stack item : INTEGER --the top item Is_empty : BOOLEAN --is the stack empty? > Initialize > put (i : INTEGER) --put ‘I’ onto the top of stack remove --remove the top item STACK Eiffel Naming Conventions

23John J. Anthony Object Oriented Programming & Design Principle 2 Separate basic queries from derived queries Derived queries can be specified in terms of queries.

24John J. Anthony Object Oriented Programming & Design Principle 3 For each derived query, write a postcondition that specifies what result will be returned in terms of one or more basic queries. Then, if we know the values of the basic queries, we also know the values of the derived queries.

25John J. Anthony Object Oriented Programming & Design Principle 2 & 3 Is_empty : BOOLEAN --does the stack contain no items ….ensure consistent_with_count: Result = (count = 0) The assertion is defined in terms of the count query. if(count > 0) Result := false elseResult :=true Principle 2 Since is_empty is derived from count Principle 3 Since postcondition is defined in terms of count

26John J. Anthony Object Oriented Programming & Design Revised Stack > count: INTEGER --the number of items on the stack item : INTEGER --the top item > Is_empty : BOOLEAN --is the stack empty? > Initialize > put (i : INTEGER) --put ‘I’ onto the top of stack remove --remove the top item STACK

27John J. Anthony Object Oriented Programming & Design Principle 4 For each command, write a postcondition that specifies the value of every basic query. Taken together with the principle of defining derived queries in terms of basic queries, this means that we know the total visible effect of each command.

28John J. Anthony Object Oriented Programming & Design Principle 4 put (I : INTEGER) --push ‘I’ onto the top of the stack ….ensure count_increased: count = old count + 1 g_on_top: item = i Count increased by 1 Top of stack equal to i

29John J. Anthony Object Oriented Programming & Design Principle 4 initialize --initialize the stack to be empty ….ensure stack_contains_zero_items: count = 0 count set to 0 What about the second basic query; item????

30John J. Anthony Object Oriented Programming & Design Principle 4 item --return the top item of the stack require stack_not_empty: count > 0 Count must be greater than 0 in order to call item Now, our contract on initialize ensures that: the value of count is zero the top item has no value

31John J. Anthony Object Oriented Programming & Design Principle 4 remove --delete the top item require stack_not_empty: count > 0 ensure count_decreased: count = old count - 1 top_item_removed: Result = old item Ensures that we do not try to remove an item from an empty stack.

32John J. Anthony Object Oriented Programming & Design Principle 5 For every query and command, decide on a suitable precondition. Preconditions constrain when clients may call the queries and commands.

33John J. Anthony Object Oriented Programming & Design Principle 6 Write invariants to define unchanging properties of objects. Concentrate on properties that help the reader build an appropriate conceptual model of the abstraction that the class embodies.

34John J. Anthony Object Oriented Programming & Design Principle 6 invariant count_never_negative: count > 0

35John J. Anthony Object Oriented Programming & Design Contracts and Inheritance How are contracts inherited from parent classes. How are contracts inherited from parent classes. How can contracts be redefined? How can contracts be redefined? How can we construct subclasses that respect the parent’s contract? How can we construct subclasses that respect the parent’s contract?

36John J. Anthony Object Oriented Programming & Design ClientSupplier ObligationPrecondition Don’t ask for delivery of packages over 5 lbs in weight Postcondition Deliver package within 3 working hours BenefitPostcondition Get package delivered within 3 working hours. Precondition Don’t have to cope with packages over 5 lbs in weight. Remember…. Back to Courier Example

37John J. Anthony Object Oriented Programming & Design Courier Class class COURIER feature deliver (p : PACKAGE, d : DESTINATION) --deliver package to destination require --weight of package p does not exceed 5 lbs. …….ensure --package delivered within 3 working hours …….end

38John J. Anthony Object Oriented Programming & Design Remember Polymorphism? Courier Different_Courier Client a_courier : Different_Courier > a_client : Client 1. A client is given access to a courier object 2. The client thinks it is using a deliver service from a regular kind of courier. 3. But the service is actually provided by a different kind of courier…. will the service be acceptable to the client? deliver(…)

39John J. Anthony Object Oriented Programming & Design Consider New Preconditions weight of package must not exceed 8 lbs weight of package must not exceed 8 lbs weight of package must not exceed 3 lbs weight of package must not exceed 3 lbs weight of package must not exceed 2 lbs weight of package must not exceed 2 lbs Which precondition(s) are acceptable?

40John J. Anthony Object Oriented Programming & Design Consider New Postconditions package will be delivered within 2 hours package will be delivered within 2 hours package will be delivered in 3 working hours package will be delivered in 3 working hours package will be delivered in 5 working hours package will be delivered in 5 working hours Which postcondition(s) are acceptable?

41John J. Anthony Object Oriented Programming & Design Different_Courier class DIFFERENT_COURIER feature deliver (p : PACKAGE, d : DESTINATION) --deliver package to destination require else --weight of package p does not exceed 8 lbs. ……. ensure then --package delivered within 2 working hours …….end

42John J. Anthony Object Oriented Programming & Design Complete Precondition deliver (p : PACKAGE, d : DESTINATION) --deliver package to destination require --weight of package p does not exceed 5 lbs. require else --weight of package p does not exceed 8 lbs. Weight of package does not exceed 5 lbs. or else Weight of package does not exceed 8 lbs.

43John J. Anthony Object Oriented Programming & Design Complete Postcondition deliver (p : PACKAGE, d : DESTINATION) --deliver package to destination ensure --package delivered within 3 working hours ensure then -- package delivered within 2 working hours Package delivered within 3 working hours and then Package delivered within 2 working hours

44John J. Anthony Object Oriented Programming & Design Benefits of Design by Contract Benefits include: Achieving better designs Achieving better designs Improving reliability Improving reliability Getting better documentation Getting better documentation

45John J. Anthony Object Oriented Programming & Design Better Designs More Systematic Designs More Systematic Designs Designers are encouraged to think about such as matters as preconditions and postconditions resulting in concepts being more explicit. Designers are encouraged to think about such as matters as preconditions and postconditions resulting in concepts being more explicit. Clearer Designs Clearer Designs The obligations and benefits are shared between the client and the suppler and are clearly stated. The obligations and benefits are shared between the client and the suppler and are clearly stated. Simpler Designs Simpler Designs Limitations on the use of a routine are clearly expressed in its precondition, and the consequences of calling it illegally are clear. Limitations on the use of a routine are clearly expressed in its precondition, and the consequences of calling it illegally are clear. Systematic Use of Exceptions Systematic Use of Exceptions Exceptions are thrown when a routine is used illegally (false precondition) or when a routine fails to fulfill its contract (false postcondition)…and nothing in between Exceptions are thrown when a routine is used illegally (false precondition) or when a routine fails to fulfill its contract (false postcondition)…and nothing in between

46John J. Anthony Object Oriented Programming & Design Improved Reliability Better Understood and Hence More Reliable Code Better Understood and Hence More Reliable Code Separates the contract code from the implementation code. Requires the implementer to think about the “specification” from two perspectives. Separates the contract code from the implementation code. Requires the implementer to think about the “specification” from two perspectives. Better Tested and Hence More Reliable Code Better Tested and Hence More Reliable Code Assertions are checked at runtime, thereby testing that routines fulfill their stated contracts. (A formal approach to test-driven development) Assertions are checked at runtime, thereby testing that routines fulfill their stated contracts. (A formal approach to test-driven development)

47John J. Anthony Object Oriented Programming & Design Better Documentation Clearer Documentation Clearer Documentation Contracts form part of the public, or client, view of a class.. Contracts form part of the public, or client, view of a class.. More Reliable Documentation More Reliable Documentation Assertions are checked at runtime, thereby testing that the stated contracts are consistent with what the routines actually do. Assertions are checked at runtime, thereby testing that the stated contracts are consistent with what the routines actually do.