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.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Chapter 13 Abstraction and inheritance. This chapter discusses n Implementing abstraction. u extension u inheritance n Polymorphism/dynamic binding. n.
Chapter 6 Conditions. This chapter discusses n Conditions and conditional statements. n Preconditions, postconditions, and class invariants. n Boolean.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 4 Parameters and Overloading. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 4-2 Learning Objectives Parameters Call-by-value Call-by-reference.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 18 Program Correctness To treat programming.
0 - 0.
Addition Facts
Lecture 10 Methods COMP1681 / SE15 Introduction to Programming.
Lecture 10 Flow of Control: Loops (Part 2) COMP1681 / SE15 Introduction to Programming.
Copyright 2012, 2008, 2004, 2000 Pearson Education, Inc.
Lecture 15 Linked Lists part 2
Extensible Networking Platform CSE 240 – Logic and Discrete Mathematics Review: Mathematical Induction Use induction to prove that the sum of the.
Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Prof. Dr. Bertrand Meyer Exercise Session 5.
Main Index Contents 11 Main Index Contents Shifting blocks of elements… Shifting blocks of elements… Model of a list object… Model of a list object… Sample.
11-Jun-14 The assert statement. 2 About the assert statement The purpose of the assert statement is to give you a way to catch program errors early The.
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.
Color Templates Software Engineering Module: Core of Java Topic: Constructors TALENTSPRINT | © Copyright 2012.
Copyright © 2012, 2008, 2004 Pearson Education, Inc. Mrs. Rivas International Studies Charter School. Bell Ringer.
Cs205: engineering software university of virginia fall 2006 Specifying Procedures David Evans
1.A computer game is an example of A.system software; B.a compiler; C.application software; D.hardware; E.none of the above. 2.JVM stands for: A.Java Virtual.
1 Chapter 4 The while loop and boolean operators Samuel Marateck ©2010.
Control Structures Selections Repetitions/iterations
Addition 1’s to 20.
Test B, 100 Subtraction Facts
Starting Out with Java: From Control Structures through Objects
Karlstad University Computer Science Design Contracts and Error Management Design Contracts and Errors A Software Development Strategy Eivind J. Nordby.
An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 14: Sorting and Searching.
Introduction to Recursion and Recursive Algorithms
Data Abstraction II SWE 619 Software Construction Last Modified, Spring 2009 Paul Ammann.
The Fundamental Rule for Testing Methods Every method should be tested in a program in which every other method in the testing program has already been.
 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.
Object Oriented Design An object combines data and operations on that data (object is an instance of class) data: class variables operations: methods Three.
Software Testing and Quality Assurance
Information Hiding and Encapsulation
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.
Component-Based Software Engineering Components and Interfaces Paul Krause.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
111 Protocols CS 4311 Wirfs Brock et al., Designing Object-Oriented Software, Prentice Hall, (Chapter 8) Meyer, B., Applying design by contract,
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
 An important topic: preconditions and postconditions.  They are a method of specifying what a method accomplishes. Preconditions and Postconditions.
Pre- and postconditions, Using assertions and exceptions 1 Pre- and postconditions Using assertions and exceptions.
Chapter 9 Putting together a complete system. This chapter discusses n Designing a complete system. n Overview of the design and implementation process.
Class Design I Class Contracts Readings: 2 nd Ed: Section 9.5, Advanced Topic nd Ed: Section 8.5, Advanced Topic 8.2 Some ideas come from: “Practical.
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.
Defensive Programming CNS 3370 Copyright 2003, Fresh Sources, Inc.
PROGRAMMING PRE- AND POSTCONDITIONS, INVARIANTS AND METHOD CONTRACTS B MODULE 2: SOFTWARE SYSTEMS 13 NOVEMBER 2013.
An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 8: Putting a System Together.
The Java Assertion. 2 Assertion A Java statement in JDK 1.4 & newer Intent: enables code to test assumptions. E.g., a method that calculates the a particle’s.
CSSE501 Object-Oriented Development. Chapter 10: Subclasses and Subtypes  In this chapter we will explore the relationships between the two concepts.
Chapter 2 Comments, Conditions, Assertions Comments Preconditions Postconditions Assertions.
1 Introduction 1. Why Data Structures? 2. What AreData Structure? 3. Phases of Software Development 4. Precondition and Postcondition 5. Examples.
Chapter 7 Programming by contract: preconditions and postconditions.
Defining Classes I Part B. Information hiding & encapsulation separate how to use the class from the implementation details separate how to use the class.
1 Exceptions When the Contract is Broken. 2 Definitions A routine call succeeds if it terminates its execution in a state satisfying its contract A routine.
Chapter 1 The Phases of Software Development. Software Development Phases ● Specification of the task ● Design of a solution ● Implementation of solution.
1 Sections 7.2 – 7.7 Nested Control Statements Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Introduction To Repetition The for loop
Topics: jGRASP editor ideosyncrasies assert debugger.
Chapter 4 : Conditionals
slides created by Ethan Apter
Programming in Java Assertion.
Chapter 6 Conditions.
slides created by Ethan Apter
Assertions References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 4/25/2019.
Computer Science 340 Software Design & Testing
slides created by Ethan Apter and Marty Stepp
Presentation transcript:

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

1May 2004Chapter5 Objectives zAfter studying this chapter you should understand the following: yprogramming by contract, defensive programming, and difference between the two; yconsequences of a clients lack of adherence to a contract; ypurpose and use of the assert statement. zAlso, you should be able to: yexpress the responsibilities of client and server as a contract; yuse assert statements to verify a clients preconditions; yuse contract to reason about a programs behavior.

2May 2004Chapter5 Method specifications zClient could give negative values. Specification of Explorers constructor allows for any int value for strength and tolerance: public Explorer (String name, Room location, int strength, int tolerance)

3May 2004Chapter5 Documenting requirements /** * Create a new Explorer with the specified name, * initial location, strength, and tolerance. * >= 0 * tolerance >= 0 * location belong to maze * name.length() > 0 */ public Explorer (String name, Room location, int strength, int tolerance)

4May 2004Chapter5 Programming by contract zProgramming style in which invocation of a method is viewed as a contract between client and server, with each having explicitly stated responsibilities.

5May 2004Chapter5 Programming by contract zPreconditions: requirements on client of a method. yLabeled require z Postconditions: requirements on server of a method. ylabeled ensure zPreconditions and postconditions are part of the contract.

6May 2004Chapter5 Programming by contract zFor method invocation to be correct: yclient must make sure that preconditions are satisfied at time of call. yIf preconditions are satisfied, server guarantees that postconditions will be satisfied when method completes otherwise server promises nothing at all.

7May 2004Chapter5 Programming by contract zConsequence: test for every possible error condition only once. yProgram efficiency. yReduction of implementation complexity.

8May 2004Chapter5 Programming by contract zComplete specification of Explorers constructor: /** * Create a new Explorer with the specified name, * initial location, strength, and tolerance. * >= 0 * tolerance >= 0 *this.name().equals(name) * this.location() == location * this.strength() == strength * this.tolerance() == tolerance */ public Explorer (String name, Room location, int strength, int tolerance)

9May 2004Chapter5 Implicit preconditions and postconditions zImplicit Preconditions: yObject arguments must be not null. yType arguments imply a range of legal values. zImplicit postconditions: yObject result will be not null. yType result implies a range of value of possible result.

10May 2004Chapter5 Verifying preconditions zThe boolean expression is evaluated yif true, statement has no effect. yIf false, statement raises an error condition stopping execution of program displaying cause of error. Javas assert statement can be used in verifying preconditions. assert booleanExpression ;

11May 2004Chapter5 Verifying preconditions public Explorer (String name, Room location, int strength, int tolerance) { assert strength >= 0; assert tolerance >= 0; this.name = name; this.location = location; this.strength = strength; this.tolerance = tolerance; }

12May 2004Chapter5 Verifying preconditions (v.2) public Explorer (String name, Room location, int strength, int tolerance) { assert strength >= 0 :"precondition: strength ("+ strength + ") >= 0"; assert tolerance >= 0 : "precondition: tolerance (" + tolerance + ") >= 0"; this.name = name; this.location = location; this.strength = strength; this.tolerance = tolerance; }

13May 2004Chapter5 Pile specification zPile instance models a pile of sticks from which players in turn removed 1, 2, or 3 sticks. Command remove : public void remove (int number) Reduce the number of sticks by the specified amount.

14May 2004Chapter5 Pile specification zQuestions: what if number is negative? Is legal? If so, what does this mean? what if number is greater than the number of sticks remaining the pile? what if number is not 1, 2, or 3?

15May 2004Chapter5 Pile specification zNot meaningful for a client to remove a negative number of sticks. zRemoving more sticks than there are in pile also seems likely to be a client error. zNumber of sticks than can legally be removed by a player is determined by rules of the game. zNot Piles responsibility.

16May 2004Chapter5 Pile complete specifications public void remove (int number) Reduce the number of sticks by the specified amount. require: number >= 0 number <= this.sticks() ensure : this.sticks() == old.sticks() - number

17May 2004Chapter5 When to write method pre-conditions zi. Method needs to have object in a certain state. Client must know state of object. public void deleteFront(){…} public void add(Student s) {…}

18May 2004Chapter5 When to write method pre-conditions zii. Method has parameters. Client must know expected parameter value. public int distanceTo(Date other){…} public void add(int x) {…}

19May 2004Chapter5 When to write method pre-conditions ziii. Method must follow a certain order in its execution. public String search(String pattern){…} public int totalPoints(){…}

20May 2004Chapter5 When to write method post-conditions zAlways. Methods return values or change state of object. zFor queries: Postcondition states what is computed. zFor commands, client must know state of object after the invocation of the method. This state is described using the corresponding queries NOT private instance variables. public void insert(int x){…}

21May 2004Chapter5 Preconditions summary zPreconditions must be satisfied by client when invoking method. zOccasionally, preconditions constrain order in which methods can be invoked or require that an object be in a certain state before invocation. yIt might be necessary that a door be unlocked before it can be opened, or that an automobile be started before it can be moved. zMost often preconditions constrain values that client can provide as arguments when invoking method. zRemember: if an argument is not constrained by a precondition, method must be prepared to accept any value of the specified type.

22May 2004Chapter5 Query postconditions summary zQuery postconditions say something about value returned.

23May 2004Chapter5 Command postconditions summary zCommands result in a change of state. zCommand postconditions describe new state of the object after execution of command. zNew state is often compared to the previous state, the state of the object before command was invoked. We use old to refer to state before call

24May 2004Chapter5 Constructor postconditions summary zConstructor postconditions describe the initial state of the newly created object.

25May 2004Chapter5 Preconditions, postconditions part of the specification zThey should never mention private implementation components. public void reset () Reset the count to 0. ensure: count == 0 This is not correct! count is private.

26May 2004Chapter5 Preconditions, postconditions part of the specification The method currentCount is part of the public specification of the class. public void reset () Reset the count to 0. ensure: this.currentCount() == 0

27May 2004Chapter5 Enumeration classes In class TrafficSignal used constants to define a type with only a 3 int values: yTrafficSignal.GREEN yTrafficSignal.YELLOW yTrafficSignal.RED In class PlayingCard used constants to define a type with four possible int values for suit, and thirteen values for rank.

28May 2004Chapter5 Enumeration classes zUsing int values to encode user defined type values as in TrafficLight or PlayingCard provides not guarantee that user will use integers in the appropriate range. PlayingCard card = new PlayingCard(27, -4); zThat is syntactically correct code but not legal values to create a card.

29May 2004Chapter5 Enumeration classes zInstead of using int values to encode user defined type values use enumeration classes. zExample: PlayingCard. yInside this class define two enumeration classes: public enum Suit { clubs, diamonds, hearts, spades); public enum Rank { two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace} Class Suit consists of four objects named clubs, diamonds, hearts, spades. Class Rank consists of 13 objects named two, three, four, …

30May 2004Chapter5 Enumeration classes zAn enum declaration defines a public static, member class. ySo, you can import the enum values using an static import statement. zIn an enumeration class method toString() is define to return the name of the enum object as a String. PlayingCard.Suit.clubs.toString() clubs

31May 2004Chapter5 Summary zIntroduced a programming style called programming by contract. zBasic idea is to make explicit responsibilities of client and server in a method invocation. zInvocation of a server method by client is viewed as a contract between the client and the server. yServer promises to perform action specified by method and to ensure that methods postconditions are satisfied, but only if yClient meets the preconditions.

32May 2004Chapter5 Summary zPreconditions are clients responsibility; zPostconditions are the servers. zIf the client fails to meet the preconditions, the contract is void: the server is not obligated to behave in any specific way.

33May 2004Chapter5 Summary zPreconditions can be verified using Javas assert statement. yIf the boolean expression in the assert statement is true, the statement has no effect. yIf it is false, an error exception occurs and the program terminates.

34May 2004Chapter5 Summary zPreconditions constrain values a client can provide as argument. zPostconditions for a query generally say something about the value returned. zPostconditions for a command describe state of the object after command is completed in terms of state before the command was begun.