An Introduction to Programming and Object Oriented Design
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
Objectives z After studying this chapter you should understand the following: yprogramming by contract, defensive programming, and difference between the two; yconsequences of a client’s lack of adherence to a contract; ypurpose and use of the assert statement. z Also, you should be able to: yexpress the responsibilities of client and server as a contract; yuse assert statements to verify a client’s preconditions; yuse contract to reason about a program’s behavior. May 2004 Chapter 5 1
Method specifications z Specification of Explorer’s constructor allows for any int value for strength and tolerance: public Explorer (String name, Room location, int strength, int tolerance) z Client could give negative values. May 2004 Chapter 5 2
Documenting requirements /** * Create a new Explorer with the specified name, * initial location, strength, and tolerance. * * @require strength >= 0 * tolerance >= 0 * location belong to maze * name. length() > 0 */ public Explorer (String name, Room location, int strength, int tolerance) May 2004 Chapter 5 3
Programming by contract z Programming style in which invocation of a method is viewed as a contract between client and server, with each having explicitly stated responsibilities. May 2004 Chapter 5 4
Programming by contract z Preconditions: requirements on client of a method. y. Labeled “require” z Postconditions: requirements on server of a method. ylabeled “ensure” z Preconditions and postconditions are part of the contract. May 2004 Chapter 5 5
Programming by contract z For method invocation to be correct: yclient must make sure that preconditions are satisfied at time of call. y. If preconditions are satisfied, server guarantees that postconditions will be satisfied when method completes otherwise server promises nothing at all. May 2004 Chapter 5 6
Programming by contract z Consequence: test for every possible error condition only once. y. Program efficiency. y. Reduction of implementation complexity. May 2004 Chapter 5 7
Programming by contract z Complete specification of Explorer’s constructor: /** * Create a new Explorer with the specified name, * initial location, strength, and tolerance. * * @require strength >= 0 * tolerance >= 0 * @ensure * this. name(). equals(name) * this. location() == location * this. strength() == strength * this. tolerance() == tolerance */ public Explorer (String name, Room location, int strength, int tolerance) May 2004 Chapter 5 8
Implicit preconditions and postconditions z Implicit Preconditions: y. Object arguments must be not null. y. Type arguments imply a range of legal values. z Implicit postconditions: y. Object result will be not null. y. Type result implies a range of value of possible result. May 2004 Chapter 5 9
Verifying preconditions z Java’s assert statement can be used in verifying preconditions. assert boolean. Expression ; z The boolean expression is evaluated yif true, statement has no effect. y. If false, statement raises an error condition stopping execution of program displaying cause of error. May 2004 Chapter 5 10
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; } May 2004 Chapter 5 11
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; } May 2004 Chapter 5 12
Pile specification z Pile instance models a pile of sticks from which players in turn removed 1, 2, or 3 sticks. z Command remove : public void remove (int number) Reduce the number of sticks by the specified amount. May 2004 Chapter 5 13
Pile specification z Questions: ywhat if number is negative? Is legal? If so, what does this mean? ywhat if number is greater than the number of sticks remaining the pile? ywhat if number is not 1, 2, or 3? May 2004 Chapter 5 14
Pile specification z Not meaningful for a client to remove a negative number of sticks. z Removing more sticks than there are in pile also seems likely to be a client error. z Number of sticks than can legally be removed by a player is determined by rules of the game. z Not Pile’s responsibility. May 2004 Chapter 5 15
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 May 2004 Chapter 5 16
When to write method pre-conditions z i. Method needs to have object in a certain state. Client must know state of object. public void delete. Front(){…} public void add(Student s) {…} May 2004 Chapter 5 17
When to write method pre-conditions z ii. Method has parameters. Client must know expected parameter value. public int distance. To(Date other){…} public void add(int x) {…} May 2004 Chapter 5 18
When to write method pre-conditions z iii. Method must follow a certain order in its execution. public String search(String pattern){…} public int total. Points(){…} May 2004 Chapter 5 19
When to write method post-conditions z Always. Methods return values or change state of object. z For queries: Postcondition states what is computed. z For 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){…} May 2004 Chapter 5 20
Preconditions summary z Preconditions must be satisfied by client when invoking method. z Occasionally, preconditions constrain order in which methods can be invoked or require that an object be in a certain state before invocation. y It might be necessary that a door be unlocked before it can be opened, or that an automobile be started before it can be moved. z Most often preconditions constrain values that client can provide as arguments when invoking method. z Remember: if an argument is not constrained by a precondition, method must be prepared to accept any value of the specified type. May 2004 Chapter 5 21
Query postconditions summary z Query postconditions say something about value returned. May 2004 Chapter 5 22
Command postconditions summary z Commands result in a change of state. z Command postconditions describe new state of the object after execution of command. z New state is often compared to the previous state, the state of the object before command was invoked. z We use “old” to refer to state before call May 2004 Chapter 5 23
Constructor postconditions summary z Constructor postconditions describe the initial state of the newly created object. May 2004 Chapter 5 24
Preconditions, postconditions part of the specification z They should never mention private implementation components. public void reset () Reset the count to 0. ensure: count == 0 May 2004 This is not correct! count is private. Chapter 5 25
Preconditions, postconditions part of the specification z The method current. Count is part of the public specification of the class. public void reset () Reset the count to 0. ensure: this. current. Count() == 0 May 2004 Chapter 5 26
Enumeration classes z In class Traffic. Signal used constants to define a type with only a 3 int values: y. Traffic. Signal. GREEN y. Traffic. Signal. YELLOW y. Traffic. Signal. RED z In class Playing. Card used constants to define a type with four possible int values for suit, and thirteen values for rank. May 2004 Chapter 5 27
Enumeration classes z Using int values to encode user defined type values as in Traffic. Light or Playing. Card provides not guarantee that user will use integers in the appropriate range. Playing. Card card = new Playing. Card(27, -4); z That is syntactically correct code but not legal values to create a card. May 2004 Chapter 5 28
Enumeration classes z Instead of using int values to encode user defined type values use enumeration classes. z Example: Playing. Card. y. Inside 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} z Class Suit consists of four objects named clubs, diamonds, hearts, spades. z Class Rank consists of 13 objects named two, three, four, … May 2004 Chapter 5 29
Enumeration classes z An enum declaration defines a public static, member class. y So, you can import the enum values using an static import statement. z In an enumeration class method to. String() is define to return the name of the enum object as a String. Playing. Card. Suit. clubs. to. String() “clubs” May 2004 Chapter 5 30
Summary z Introduced a programming style called programming by contract. z Basic idea is to make explicit responsibilities of client and server in a method invocation. z Invocation of a server method by client is viewed as a contract between the client and the server. y. Server promises to perform action specified by method and to ensure that method’s postconditions are satisfied, but only if y. Client meets the preconditions. May 2004 Chapter 5 31
Summary z Preconditions are client’s responsibility; z Postconditions are the server’s. z If the client fails to meet the preconditions, the contract is void: the server is not obligated to behave in any specific way. May 2004 Chapter 5 32
Summary z Preconditions can be verified using Java’s assert statement. y. If the boolean expression in the assert statement is true, the statement has no effect. y. If it is false, an error exception occurs and the program terminates. May 2004 Chapter 5 33
Summary z Preconditions constrain values a client can provide as argument. z Postconditions for a query generally say something about the value returned. z Postconditions for a command describe state of the object after command is completed in terms of state before the command was begun. May 2004 Chapter 5 34
- Slides: 35