EECE 310: Software Engineering

Slides:



Advertisements
Similar presentations
The Substitution Principle SWE 332 – Fall Liskov Substitution Principle In any client code, if subtype object is substituted for supertype object,
Advertisements

Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Data Abstraction II SWE 619 Software Construction Last Modified, Spring 2009 Paul Ammann.
5/17/2015 OO Design: Liskov Substitution Principle 1.
Testing and Inheritance What is the relation between the test suite of a superclass and a subclass?
Inheritance and object compatibility Object type compatibility An instance of a subclass can be used instead of an instance of the superclass, but not.
© 2006 Pearson Addison-Wesley. All rights reserved9 A-1 Chapter 9 Advanced Java Topics.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 CS4850 Programming Languages Wuwei Shen. 2 Aministrivia Course home page: Reference books: –Programming Languages,
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
1 Topic 4 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“
Chapter 10 Classes Continued
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
1 Abstraction  Identify important aspects and ignore the details  Permeates software development programming languages are abstractions built on hardware.
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
EECE 310: Software Engineering Iteration Abstraction.
Low-Level Detailed Design SAD (Soft Arch Design) Mid-level Detailed Design Low-Level Detailed Design Design Finalization Design Document.
Class Design III: Advanced Inheritance Additional References “Object-Oriented Software Development Using Java”, Xiaoping Jia, Addison Wesley, 2002 “Core.
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
Software Design Principles
1 Single Responsibility Principle Open Closed Principle Liskov Substitution Principle Law of Demeter CSC 335: Object-Oriented Programming and Design.
Testing and Inheritance What is the relation between the test suite of a superclass and a subclass?
Types in programming languages1 What are types, and why do we need them?
Type Abstraction Liskov, Chapter 7. 2 Liskov Substitution Principle In any client code, if the supertype object is substituted by a subtype object, the.
Data Abstractions EECE 310: Software Engineering.
Type Abstraction SWE Spring October 05Kaushik, Ammann Substitution Principle “In any client code, if supertype object is substituted.
Polymorphism Liskov 8. Outline equals() Revisiting Liskov’s mutable vs. not rule Polymorphism Uniform methods for different types “easy” polymorphism.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
1. Perspectives on Design Principles – Semantic Invariants and Design Entropy Catalin Tudor 2.
CSSE501 Object-Oriented Development. Chapter 10: Subclasses and Subtypes  In this chapter we will explore the relationships between the two concepts.
Cs2220: Engineering Software Class 12: Substitution Principle Fall 2010 University of Virginia David Evans.
Test Code Patterns How to design your test code. 2 Testing and Inheritance Should you retest inherited methods? Can you reuse superclass tests for inherited.
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.
Recitation 7 Godfrey Tan March 21, Administrivia PS6 due Tuesday right after break Final Project descriptions will be handed out Monday after break.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
EECE 310: Software Engineering
Modern Programming Tools And Techniques-I
EECE 310: Software Engineering
Inheritance ITI1121 Nour El Kadri.
Design by Contract Jim Fawcett CSE784 – Software Studio
Design by Contract Jim Fawcett CSE784 – Software Studio
Multi-Methods in Cecil
Inheritance and Polymorphism
CSE 331 Subtyping slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Week 4 Object-Oriented Programming (1): Inheritance
Type Abstraction SWE Spring 2009.
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Subtype Polymorphism, Subtyping vs
Lecture 22 Inheritance Richard Gesick.
slides created by Ethan Apter
Week 6 Object-Oriented Programming (2): Polymorphism
Type Abstraction Liskov, Chapter 7.
Topic 4 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“
Iteration Abstraction
slides created by Ethan Apter
EECE 310: Software Engineering
CIS 199 Final Review.
Final and Abstract Classes
slides created by Ethan Apter and Marty Stepp
Type Abstraction SWE Spring 2013.
CMPE212 – Reminders Assignment 2 due next Friday.
slides created by Ethan Apter
C++ Object Oriented 1.
CIS 110: Introduction to computer programming
Presentation transcript:

EECE 310: Software Engineering Type Hierarchies and the Substitution Principle

Objectives Apply the Liskov Substitution Principle (LSP) to the design of type hierarchies Use abstract base classes to solve LSP problem Decide when to favor composition over inheritance and vice versa

NonEmptySet Type Consider a subtype of IntSet called non-empty set, with the stipulation that it must *never* be empty. i.e., it has at least 1 element always Constructor takes the element as an argument and adds it to the els vector (the rep) insert, size, isIn work as before (no change) remove must make sure it never leaves the set empty, otherwise it throws an EmptySetException

NonEmptySet: Remove public class NonEmptySet extends IntSet { … public void remove(int x) throws EmptySetException { // EFFECTS: If set has at least two elements, // then remove x from the set // Otherwise, throw the EmptySetException …. }

RemoveAny procedure public static boolean removeAny(IntSet s) { // EFFECTS: Remove an arbitrary element from // the IntSet if the set is not empty, return true // Otherwise do nothing and return false if (s.size() == 0) return false; int x = s.choose(); s.remove(x); return true; }

Usage of removeAny IntSet s = new IntSet(); … // Add elements to s while ( removeAny(s) ) { } // s is empty at this point

What about this one ? IntSet s = new NonEmptySet(3); … // Add elements to s while ( removeAny(s) ) { } // control never reaches here ! Can potentially throw an EmptySet exception !

Liskov Substitution principle Intuition Users can use and reason about subtypes just using the supertype specification. Definition Subtype specification must support reasoning based on the super-type specification according to following rules: signature rule methods rule properties rule 1. The code should behave the same way a supertype would have even when subtype is used

Signature Rule Every call that is type-correct with the super-type objects must also be type-correct with the sub-type objects Sub-type objects must have all the methods of the super-type Signatures of the subtype’s implementations must be compatible with the signatures of the corresponding super-type methods

Signature Rule in Java Subtype’s method can have fewer exceptions but NOT throw more exceptions Arguments and return type should be identical: (stricter than necessary) Foo clone(); Foo x = y.clone(); Object clone(); Foo x = (Foo) y.clone(); Enforced by the compiler at compile-time Subtypes can have fewer exceptions Enforced by the compiler

NonEmptySet: Remove public class NonEmptySet extends IntSet { … public void remove(int x) throws EmptySetException { // EFFECTS: If set has at least two elements, // then remove x // Otherwise, throw the EmptySetException …. } Violates signature rule – will not compile

Will this solve the problem ? public class NonEmptySet extends IntSet { … public void remove(int x) { // EFFECTS: If set has at least two elements, // then remove x // Otherwise, do nothing …. }

What will happen in this case ? IntSet s = new NonEmptySet(3); … // Add elements to s while ( removeAny(s) ) { } // control never reaches here ! Will loop forever because the set never becomes empty (why ?)

What’s the problem here ? The remove method of NonEmptyIntSet has a different behavior than the remove method of the IntSet ADT (it’s parent type) In the IntSet ADT, after you call remove(x), you are assured that x is no longer part of the set (provided the set was non-empty prior to the call) In the NonEmptyIntSet ADT, after you call remove(x), you do not have this assurance anymore which violates the substitution principle

Methods rule A sub-type method can weaken the pre-condition (REQUIRES) of the parent method and strengthen its post-condition (EFFECTS) Pre-condition rule: presuper=> presub Post-condition rule: presuper && postsub => postsuper Both conditions must be satisfied to achieve compatibility between the sub-type and super-type methods

Remember … Weakening of pre-condition: REQUIRES less Example: Parent-type requires a non-empty collection, but the sub-type does not Example: Parent-type requires a value > 0, sub-type can take a value >=0 in its required clause Strengthening of post-condition: DOES more Example: Sub-type returns the elements of the set in sorted order while parent-type returns them in any arbitrary order (sorted => arbitrary)

Example of methods rule Consider a sub-type of IntSet LogIntSet which keeps track of all elements that were ever in the set even after they are removed public void insert(int x) // MODIFIES: this // EFFECTS: Adds x to the set and to the log Does this satisfy the methods rule ?

Is the methods rule satisfied here ? Consider another sub-type PositiveIntSet which only adds positive Integers to the set public void insert(int x) // MODIFIED: this // EFFECTS: if x >= 0 adds it to this // else does nothing

Back to the NonEmptySet Type public class NonEmptySet { // Not derived from IntSet // A Non-empty IntSet is a mutable set of integers // whose size is at least 1 always public void removeNonEmpty(int x) { // EFFECTS: If set has at least two elements, // then remove x // Otherwise, do nothing …. }

Regular IntSet public class IntSet extends NonEmptySet { // Overview: A regular IntSet as before public void remove(int x) { // MODIFIES: this // EFFECTS: Removes x from this … }

What happens in this code ? public static void findMax (NonEmptySet s) { int max = s.choose(); iterator g = s.elements(); while (g.hasNext() ) { … } Can throw an exception if IntSet is passed in as argument

What’s the problem here ? The IntSet type has an operation remove which causes it to violate the invariant property of its parent type NonEmptySet Calling code may be able to make the set empty by calling remove and then pass it to findMax Not enough if the derived methods preserve the parent-type’s invariant, the new methods in sub-type must do so as well

Properties Rule Subtype must preserve each property of the super-type in each of its methods Invariant properties (always true) Evolution properties (evolve over time) Examples Invariant property: The set never becomes empty Evolution property: The set size never decreases

Putting it together: Substitution Principle Signature rule: If program is type-correct based on super-type specification, it is also type-correct with respect to the sub-type specification. Methods rule: Ensures that reasoning about calls of super-type methods is valid even if the call goes to code that implements a subtype. Properties rule: Reasoning about properties of objects based on super-type specification is still valid even when objects belong to the sub-type.

Summary of LSP Liskov Substitution Principle (LSP) is a unifying way of reasoning about the use of sub-types Signature rule: Syntactic constraint and can be enforced by compiler Methods rule and properties rule: Pertain to semantics (behavior) and must be enforced by programmer LSP is essential for locality and modifiability of programs using types and sub-types

Group Activity In the handout

Objectives Apply the Liskov Substitution Principle (LSP) to the design of type hierarchies Use abstract base classes to solve LSP problem Decide when to favor composition over inheritance and vice versa

Why do we use sub-types ? Define relationships among a group of types SortedList and UnsortedList are sub-types of List Specification reuse (common interface) Using code simply says “give me a list” Implementation reuse (code sharing) SortedList need not re-implement all of List’s methods Modifiability of parent type Client need not change if parent class implementation changes (if done through public interface)

Why not to use sub-types ? Sub-types are not appropriate in many cases Sub-type must satisfy Liskov Substitution Principle. In other words, it must not cause existing code to break. Subtype’s implementation must not depend on the implementation details of the parent type Common rule of thumb: “Sub-types must model is a special kind of relationship” Not always as simple or true as we will soon see

Example: Rectangle // A vanilla Rectangle class. public class Rectangle { private double width; private double height; public Rectangle(double w, double h) { width = w; height = h; } public double getWidth() {return width;} public double getHeight() {return height;} public void setWidth(double w) {width = w;} public void setHeight(double h) {height = h;}

Example: Square Sub-type ? Should we model a square as a sub-type of rectangle (isn’t square a “type of” rectangle ?) We won’t need two instance variables, height and width, but this is a minor irritant Need to override setHeight and setWidth operations so that width and height cannot be changed independently Remember, you cannot change the Rectangle class

Example: Square public class Square extends Rectangle { private double width; private double height; public Square(double s) { super(s, s); } public void setWidth(double w) { super.setWidth(w); super.setHeight(w); public void setHeight(double h) { super.setWidth(h); super.setHeight(h);

What is the problem here ? void testRectangle(Rectangle r) { r.setWidth(4); r.setHeight(5); assert( r.getHeight() * r.getWidth() == 20 ); } testRectangle( new Square(3) );

Problem Although Square is a type of rectangle in the real world, a square object is NOT a sub-type of a rectangle object because it is more constrained than the rectangle object Which rule of LSP does it break ? We should NOT model square as a sub-type of rectangle because behaviorally, a square object cannot be substituted for a rectangle object.

So how do you fix this ? Square and rectangle should not be in an inheritance relationship with one-another They are really doing two different things, just so happens they share some (minimal) features Do not satisfy the LSP (behavioral substitution) But, how to share code between two ADTs which are not in inherited from each other ?

One “Solution”: Abstract base class public abstract class Quadrilateral { // Represents a generic square or rectangle protected Quad(); // do we need this ? public int getHeight(); public int getWidth(); public abstract void setWidth(); public abstract void setHeight(); }

Abstract Base Class Abstract classes are used for providing partial implementations of data types Declared using the keyword abstract in Java May or may not have instance variables Needs to have constructors if it has instance vars Has one or more methods partially implemented, other methods are declared as abstract Sub-classes implement the abstract methods Can call the base class’s (non-abstract) methods Need not implement all abstract methods

Abstract Classes Vs. Interfaces

Class Exercise Distributed as a handout in class

Objectives Apply the Liskov Substitution Principle (LSP) to the design of type hierarchies Use abstract base classes to solve LSP problem Decide when to favor composition over inheritance and vice versa

Fragile Base Class Problem LSP is not the only problem with inheritance. Even if LSP is satisfied, there are other issues Assume that you add a new method to IntSet public void addAll(Collection<int> c) { // EFFECTS: Adds all elements of c to IntSet Iterator<int> ci = c.elements(); while (ci.hasNext()){ this.add( c.next() ); }

InstrumentedIntSet Consider an example InstrumentedIntSet which keeps track of the number of elements ever added to the IntSet ADT (different from its size). Assume this type inherits from IntSet Must add a new field to keep track of count Override the add method to increment count Override the addAll method to increment count

InstrumentedIntSet: Inheritance public class InstrumentedIntSet extends IntSet { private int addCount; // The number of attempted element insertions public InstrumentedIntSet() { super(); addCount = 0; } public boolean add(Object o) { addCount++; return super.add(o); } public boolean addAll(Collection<int> c) { addCount += c.size(); return super.addAll(c); public int getAddCount() { return addCount;

What’s the problem here ? Consider the following code: IntSet s = new InstrumentedIntSet(); Vector v = new Vector<int>(); // Assume that vector v has 3 int elements s.addAll( v ); int i = s.getAddCount( ); // What does it return ? How will you fix this problem ? 1. Modify addAll to not do the increment, but what if base class does not call the add method? 2. Write your own version of addAll in the derived class to do the iteration (no reuse)

Solution: Use Composition Instead of making InstrumentedIntSet a sub-type of IntSet, make it contain an IntSet In Java, it holds a reference to an IntSet rather than a copy, so be careful to not expose it Do not have to worry about substitution principle (though that is not a problem in this example) Make both classes implement a common Set interface if you want them to be inter-changeable

InstrumentedIntSet: Composition-1 public class InstrumentedIntSet implements Set { private IntSet s; private int addCount; public InstrumentedIntSet( ) { addCount = 0; s = new IntSet(); }

InstrumentedIntSet: Composition-2 public class InstrumentedIntSet implements Set { public void add(int element) { addCount = addCount + 1; s.add(element); } public void addAll(Collection c) { addCount = addCount + c.size(); s.addAll( c );

Should B be a subtype of A ? Do we need to use B in place of A ? Start NO YES Does B satisfy the LSP ? Do B and A need to share any code ? NO NO YES YES Make B and A independent types (common interface if necessary) Make B a sub-type of A, but try to use the public interface of A in B if possible and efficient Make B contain an object of type A (common interface if necessary)

Class Exercise Consider the NonEmptySet type that we saw earlier. Can you rewrite it to use an IntSet rather than be derived from an IntSet ? How will you make them inherit from a common base class ?

Summary of Sub-typing Inheritance is often over-used without regard for its consequences (e.g., Java class library) Not always straightforward to ensure behavioral substitutability of parent-type with sub-type Subtle dependencies of sub-type on parent type’s implementation details can cause fragility Use composition instead of inheritance whenever possible (with interfaces if necessary)