The Liskov Substitution Principle

Similar documents
Software Engineering Design & Construction

equals() in the class Object

The class Object. Lecture CS1122 Summer 2008

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Super-Classes and sub-classes

Software Engineering Design & Construction Dr. Michael Eichberg Fachgebiet Softwaretechnik Technische Universität Darmstadt

For this section, we will implement a class with only non-static features, that represents a rectangle

Inheritance Systems. Merchandise. Television Camcorder Shirt Shoe Dress 9.1.1

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

CS-202 Introduction to Object Oriented Programming

Software Engineering Design & Construction Dr. Michael Eichberg Fachgebiet Softwaretechnik Technische Universität Darmstadt

Methods Common to all Classes

Abstract and final classes [Horstmann, pp ] An abstract class is kind of a cross between a class and an interface.

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

CSE 331 Software Design & Implementation

java.lang.object: Equality

ITI Introduction to Computing II

Inheritance and object compatibility

Overview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting

Equality. Michael Ernst. CSE 331 University of Washington

Some client code. output. subtype polymorphism As dynamic binding occurs the behavior (i.e., methods) follow the objects. Squarer

Programming Languages and Techniques (CIS120e)

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

Creating an Immutable Class. Based on slides by Prof. Burton Ma

Charlie Garrod Michael Hilton

Principles of Software Construction: Objects, Design and Concurrency. Polymorphism, part 2. toad Fall 2012

COMP 401 INHERITANCE: IS-A. Instructor: Prasun Dewan

Introduction to Object-Oriented Programming

Effective Java. Object Equality. - Case Studies - Angelika Langer. Trainer/Consultant.

Principles of Software Construction: Objects, Design and Concurrency. Inheritance, type-checking, and method dispatch. toad

ITI Introduction to Computing II

Expected properties of equality

CSE 331 Software Design & Implementation

Domain-Driven Design Activity

Liskov Substitution Principle

CSE wi Midterm Exam 2/8/18 Sample Solution

Java Fundamentals (II)

ITI Introduction to Computing II

Test Code Patterns. How to design your test code

Conception Orientée Objets. Programmation SOLID

Testing and Inheritance. Test Code Patterns. Inheritance-related bugs. Inheritance. Testing of Inheritance. Inheritance-related bugs

Outline. Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle. Benefits of Subtype Polymorphism. Subtype Polymorphism

COMP 250 Fall inheritance Nov. 17, 2017

Announcements. Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle. Intuition: Type Signature is a Specification.

CSE wi Midterm Exam 2/8/18. Name UW ID #

Chapter 11: Collections and Maps

Principles of Object-Oriented Design

Assertions, pre/postconditions

MET08-J. Preserve the equality contract when overriding the equals() method

Intro to: Design Principles

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

Designing Robust Classes

6.170 Recitation #5: Subtypes and Inheritance

CS/ENGRD 2110 SPRING Lecture 2: Objects and classes in Java

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Last Time: Object Design. Comp435 Object-Oriented Design. Last Time: Responsibilities. Last Time: Creator. Last Time: The 9 GRASP Patterns

Lecture 11 Subtypes and Subclasses

Uguaglianza e Identità. (no, non avete sbagliato corso )

n HW5 out, due Tuesday October 30 th n Part 1: Questions on material we ll cover today n Part 2: BFS using your graph from HW4

Inheritance (Part 5) Odds and ends

COMP 401 Fall Recitation 6: Inheritance

Inheritance and Polymorphism

Lecture 4. Types, Memory, Exceptions

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Design Principles: Part 2

Design Principles: Part 2

Outline. Design Principles: Part 2. e.g. Rectangles and Squares. The Liskov Substitution Principle (LSP) ENGI 5895: Software Design.

Last name:... First name:... Department (if not D-INFK):...

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism

INSTRUCTIONS TO CANDIDATES

CSE 373. Objects in Collections: Object; equals; compareto; mutability. slides created by Marty Stepp

CSE 331 Software Design and Implementation. Lecture 12 Subtypes and Subclasses

COMP 250. Lecture 30. inheritance. overriding vs overloading. Nov. 17, 2017

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

OO Design Principles

Software Engineering CSC40232: SOFTWARE ENGINEERING. Guest Lecturer: Jin Guo SOLID Principles sarec.nd.edu/courses/se2017

Equality in.net. Gregory Adam 07/12/2008. This article describes how equality works in.net

CS/ENGRD 2110 FALL Lecture 2: Objects and classes in Java

Classes, interfaces, & documentation. Review of basic building blocks

Java: advanced object-oriented features

Equality. Michael Ernst. CSE 331 University of Washington

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters

Object-Oriented Programming in the Java language

S.O.L.I.D: Software Engineering Principles

CLASS DESIGN. Objectives MODULE 4

CS/ENGRD 2110 SPRING Lecture 2: Objects and classes in Java

Objects and Classes (1)

An Approach to Behavioral Subtyping Based on Static Analysis

a correct statement? You need to know what the statement is supposed to do.

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

OO Technology: Properties and Limitations for Component-Based Design

Making New instances of Classes

Subtypes and Subclasses

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

Transcription:

Agile Design Principles: The Liskov Substitution Principle Based on Chapter 10 of Robert C. Martin, Agile Software Development: Principles, Patterns, and Practices, Prentice Hall, 2003 and on Barbara Liskov and Jeannette Wing, A behavioral notion of subtyping, ACM Transactions on Programming Languages and Systems (TOPLAS), vol. 16, #6, 1994. 1

The (LSP)! If S is a declared subtype of T, objects of type S should behave as objects of type T are expected to behave, if they are treated as objects of type T! Note that the LSP is all about expected behaviour of objects. One can only follow the LSP if one is clear about what the expected behaviour of objects is. Slide 2

subtypes and instances! For Java S is a declared subtype of T if " S is T, " S implements or extends T, or " S implements or extends a type that implements or extends T, and so on! S is a direct subtype of T if " S extends or implements T Slide 3

subtypes and instances! An object is a direct instance of a type T " if it is created by a new T() expression! An object is an instance of T " if it is a direct instance of a declared subtype of T. Slide 4

The (LSP)! If S is a declared subtype of T, objects of type S should behave as objects of type T are expected to behave, if they are treated as objects of type T Slide 5

Example of the LSP void someclientcode( Bag t ) { Assertion.check( t.isempty() ); t.put( new Range(0,N) ) ; while(!t.empty() ) { Range r = (Range) t.take() ; if( r.size() > 2 ) { int m = part( r ) ; t.put( new Range( r.low(), m ) ) ; t.put( new Range( m, r.high() ) ) ; } } } " Clearly the designer has some expectations about how an instance of Bag will behave. " Let S be any declared subtype of Bag. " If we pass in a direct instance of S, this code should still work. " The expectations we have for instances of Bag should hold for instances of S. Slide 6

Expectations about behaviour! Behavioural specification " The behavioural specification of a class explains the allowable behaviours of the instances of a class.! S is a behavioural subtype of T if " an instance of type S behaves only as allowed of type T objects! The LSP then says declared subtypes should be behavioural subtypes Slide 7

Expectations about behaviour! So where do these expectations about behaviour live?! In most language only a part of the expectations can be encoded in the language (for example types of parameters and results)! The rest of our expectations have to be expressed in the documentation.! [Time for an example.] Slide 8

Bags and Stacks the Bag class " State: a bag (i.e. multiset) of Objects b " isempty() : boolean! Postcondition: Returns true if and only if b is empty. " take() : Object! Precondition:! isempty()! Postcondition: result is an arbitrary member of b. The final value of b is the initial value with the result removed. " put( ob : Object )! Precondition: true! Postcondition: The final value of b is its initial value with ob added. Slide 9

Bags and Stacks the Stack class " State: a sequence of Objects s " isempty() : boolean! Precondition: true! Postcondition: returns true if and only if s is empty " take() : Object! Precondition:! isempty()! Postcondition: result is the first item of s. The final value of s is the initial value with the first item removed. " put( ob : Object )! Precondition: true! Postcondition: The final value of s is its initial value with ob prepended. Slide 10

Bags and Stacks! Stacks are more constrained than Bags.! A Stack object could be used where a Bag object is expected without violating our expectations of how a bag should behave.! Thus Stack is a behavioural subtype of Bag.! By the LSP, it is reasonable that Stack should be a declared subtype of Bag. Slide 11

Expectations about behaviour! [Now where were we?]! So where do these expectations about behaviour live?! They have to come (in part) from the documentation.! Such expectations can not come from the code, as " method implementations may be abstract " even if not abstract, method implementations can be overridden Slide 12

The counterfeit test.! Here is a way to think about behavioural subtypes: " Suppose I promise to deliver you an object of class T, but instead I give you an object x of class S. " You can subject x to any series of method calls you like (chosen from T s signature). " If x behaves in a way that is not expected of a T object, then you know it is a counterfeit, x has failed the test. " If all S objects always pass every counterfeit test, then S is a behavioural subtype of T. Slide 13

Your turn! the Square class " state: x, y, size " getx() returns x " gety() returns y " getwidth() returns size " getheight() returns size! the Rectangle class " state: x, y, width, height " getx() returns x " gety() returns y " getwidth() returns width " getheight() returns height Is Square a behavioural subtype of Rectangle? Is Rectangle a behavioural subtype of Square? Slide 14

Your turn! the MutSquare class " state: x, y, size " getx() returns x " gety() returns y " getwidth() returns size " getheight() returns size " setwidth(int w) size := w " setheight(int h) size := h Is MutSquare a behavioural subtype of Square? Is Rectangle a behavioural subtype of MutRectangle? Is MutSquare a behavioural subtype of MutRectangle? Is MutRectangle a behavioural subtype of MutSquare?! the MutRectangle class " state: x, y, width, height " getx() returns x " gety() returns y " getwidth() returns width " getheight() returns height " setwidth(int w) width := w " setheight(int h) height := h Slide 15

LSP and syntactic interfaces! As we ve seen. Semantic interfaces for subtypes can be more specific compared to the supertype.! The same applies to syntactic interfaces (in many languages). Consider two Java classes: Slide 16

LSP and syntactic interfaces class T { Object a() { } } class S extends T { } @Override String a() { }! This is allowed in Java. " More specific classes may have more specific return types " This is called covariance Slide 17

LSP and syntactic interfaces! The same applies to exceptions class T { void b( ) throws Throwable { } } class S extends T { @Override void b( ) throws IOException { } } class U extends S { } @Override void b( ) { } " Every exception declared for the subtype s method should be a subtype of some exception declared for the supertype s method. Slide 18

LSP and syntactic interfaces! Logically it could be allowed for parameters to be contravariant class T { void c( String s ) { } } class S extends T { @Override void c( Object s ) { } X }! However this is actually not allowed (in Java), as it would complicate the overloading rules Slide 19

LSP and semantic interfaces! Is this an LSP violation: class Buffer<T> { protected T[] a = new T[10] ; protected int s = 0, h = 0 ; public void add( T x ) { if( s == 10 ) { --s ; h = (h+1)%10 ; } ++s ; a[ (h+s) % 10 ] = x ; } } class SafeBuffer<T> extends Buffer<T> { @Override public void add( T x ) { if( s == 10 ) throw new AssertionError() ; ++s ; a[ (h+s) % 10 ] = x ; } } Slide 20

LSP and semantic interfaces! My answer: You can not tell.! Nothing describes how Buffers are expected to behave.! Let s document Buffer in two ways. Depending on the documentation, there either is of is not an LSP violation. Slide 21

LSP and semantic interfaces! LSP violation: class Buffer<T> { /** Expected Behaviour: * Adds a new item to the buffer, deleting * the head if space has run out. */ public void add( T x ) { } }! The behaviour of SaferBuffer is inconsistent with this expected behaviour. Slide 22

LSP and semantic interfaces! No LSP violation: class Buffer<T> { /** Expected Behaviour: * If there is space, adds an new item to the * queue. Otherwise anything could happen. */ public void add( T x ) { } }! The coded behaviour of SaferBuffer is consistent with this specification. Slide 23

Document twice! Any concrete method that may be overridden should be documented twice: " The Expected Behaviour documents what the client can expect from all instances (direct or indirect) of the class. " The Direct Behaviour documents what the client can expect from direct instance of the class! or from instances of subclasses that do not override the method. Slide 24

Document twice! This is the no-violation version. class Buffer<T> { /** Expected Behaviour: * If there is space, adds an new item to the * queue. Otherwise anything could happen. * Direct Behaviour: * Adds a new item to the buffer, deleting * the head if space has run out. */ public void add( T x ) { } } Slide 25

Document twice! Rewritten with pre- & postconditions class Buffer<T> { /** Conceptual state: a sequence q. */ /** Expected Behaviour: * pre: q.size < 10 * post: The final value of q is the initial value * of q except with x tacked on the right end. *! (continued on next slide) Slide 26

Document twice! (continued from last slide class Buffer<T> { /*. * Direct Behaviour: * pre: true * post: The final value of q is the initial value * of q except with x tacked on the right end. * and the first item removed in the case * that the initial value of q had size 10. */ public void add( T x ) { } } Slide 27

Document twice! Abstract methods: " Only need Expected Behaviours.! Final methods (methods that can t be overridden) " Only need Direct Behaviours.! Otherwise if the Direct Behaviour is undocumented, it is considered equal to the Expected Behaviour. Slide 28

Refinement! A specification X refines a specification Y iff X is at least as constraining as Y.! I.e. iff all behaviours accepted by X are also accepted by Y! Example " X: If at least 2 engines are working, the plane can maintain an altitude of at least 10,000m. " Y: If at least 3 engines are working, the plane can maintain an altitude of at least 5,000. " X refines Y Slide 29

Refinement! A specification X refines a specification Y iff X is at least as constraining as Y.! I.e. iff all behaviours accepted by X are also accepted by Y! Example " X: pre: a is positive and < 1,000,000 post: result is the square root of a to 4 place " Y: pre: a is positive and < 500,000 post: result is the square root of a to 3 places Slide 30

Refinement and classes! The following refinements should hold. " The source code of T should refine the direct behaviour of T. " The direct behaviour T should refine the expected behaviour T. " If S is a declared subtype of T, the expected behaviour of S should refine the expected behaviour of T. Slide 31

Some cases where the LSP is difficult! Like a healthy diet the LSP is obviously good for you, but it can be tempting to cheat a little.! Consider a class public class Point2D { protected double x ; protected double y ; } Slide 32

Some cases where the LSP is difficult! Consider Java s tostring method (inherited from Object) class Point2D { /** Return a string representation of the point. * Postcondition: result is a string of the form * ( xrep, yrep ) * where xrep is a string representing the x value and * yrep is a string representing the y value */ @Override public String tostring() { return ( + Double.toString(x) +, + Double.toString(y) + ) ; } } Slide 33

Some cases where the LSP is difficult! And Java s equals method. class Point2D { /** Indicate whether two points are equal. * Returns true iff the x and y values are equal. */ @Override public boolean equals(object ob) { if( ob instanceof Point2D ) { Point2D that = (Point2D) ob ; return this.x == that.x && this.y == that.y ; } else return false ; } }! So far so good. Slide 34

Some cases where the LSP is difficult! Now consider extending Point2D to Point3D public class Point3D extends Point2D { protected double z ; }! We define tostring as @Override public String tostring() { return ( + Double.toString(x) +, + Double.toString(y) +, + Double.toString(z) + ) ; } Slide 35

Some cases where the LSP is difficult! Consider: void printpoint( Point2D p ) { p.setx(1.0) ; p.sety(2.0) ; System.out.println( p.tostring() ) ; }! The behaviour will not be as expected if a Point3D is passed in.! Surely there is no problem with our code though!! The problem is with our expectations. Slide 36

Two solutions 1. Lower expectations /** Return a string representation of the point. * Postcondition: result is a string indicating at least * the x and y values. */ @Override public String tostring() { as on slide 14 } 2. Prevent overrides! It would be poor practice to prevent an override of tostring(), so I use another name. /** Return a string representation of the point. * Postcondition: as on slide 14 */ public final String tostring2d() { as on slide 14 } Slide 37

What about equals?! Naturally, equals is also overridden in Point3D. @Override public boolean equals(object ob) { if( ob instanceof Point3D ) { Point3D that = (Point3D) ob ; return this.z == that.z && super.equals( that ) ; } else return super.equals( ob ) ; }! (By the way, the reason for not just returning false, when the other object is not a Point3D, is that equals should be symmetric when neither object is null. I.e. p2.equals(p3) == p3.equals(p2) ) Slide 38

What about equals?! So the code void thisorthat( Point2D p, Point2D q ) { p.setx( x0 ) ; p.sety( y0 ) ; q.setx( x1 ) ; q.sety( y1 ) ; if( p.equals( q ) ) { do this } else { do that } } may not behave according to our expectations. (Consider the case where x0 == x1, y0 == y1, and p.z!= q.z.)! Again we have violated the LSP. Slide 39

Two Solutions 1. Reduce Expectations.! We should reword the documentation of equals for Point2D to be more flexible! /** Do two Point2D objects compare equal by the standard of their least common ancestor class? <p> At this level the standard is equality of the x and y values.*/ 2. Prevent overrides " We wouldn t want to prevent overrides of equals. We are better off providing a new name /** Are points equal as 2D points? */ public final boolean equals2d( Point2D that ) { return this.x==that.x && this.y==that.y ; } Slide 40

Lesson 0! Every class represents 2 specifications " One specifies the behaviour of its direct instances! And this can be reverse engineered from the code. " One specifies the behaviour of its instances! And this can only be deduced from its documentation.! It is important to document the behaviour that can be expected of all instances.! It is less important to document the behaviour that can be expected of direct instances.! However sometimes it is useful to do both. Slide 41

Lesson 1! When documenting methods that may be overridden,! one must be careful to document the method in a way that will make sense for all potential overrides of the function. Slide 42

Lesson 2! One should document any restrictions on how the method may be overridden.! For example consider the documentation of equals in Object. It consists almost entirely of restrictions on how the method may be overridden and thus it describes what the clients may expect. Slide 43

Documentation of Object.equals(Object)! Indicates whether some other object is "equal to" this one.! The equals method implements an equivalence relation on non-null object references: " It is reflexive: for any non-null reference value x, x.equals(x) should return true. " It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. " It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. " It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified. " For any non-null reference value x, x.equals(null) should return false.! The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true). Slide 44

Lesson 3! It is particularly important to carefully and precisely document methods that may be overridden! because one can not deduce the intended specification from the code. " For example, consider the implementation of equals in Object " public boolean equals( Object ob ) { " return this == ob ; } " compared to the documentation on the previous slide.! There may not even be any code. Slide 45

In Summary! The " demands that subtyping (extends and implements, in Java) really lives up to its is a billing. " prevents breaking client code when objects of a declared subtype are passed to it. " is thus good practice. " can not be practiced without careful and precise documentation of object behaviour. Slide 46

By the way! Martin s description is pithier: Subtypes must be substitutable for their base types! But, I have no idea what this means.! For example, if S is a subtype of T and I have a statement if( x instanceof T ) dothis() ; else dothat() ; it would be a mistake to replace T with S. And in the statement T x = new T() ; it would definitely be a mistake to replace the first T with S, and it could be a mistake to replace the second with S. Slide 47

Challenge! There is still a problem with the equals methods on points.! They violate transitivity! We could have " p3a.equals(p3b) == false but " (p3a.equals(p2) && p2.equals(p3b)) == true! My challenge to you: Find a set of contracts and implementations that truly satisfy the LSP. Slide 48