SlideShare ist ein Scribd-Unternehmen logo
1 von 51
EECE 210: Software Design
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 use composition over
inheritance
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

4
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
….
}
}
5
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;
}
6
Usage of removeAny
IntSet s = new IntSet();
…
// Add elements to s
while ( removeAny(s) ) {
…
}
// s is empty at this point
7
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 !

8
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:
1. signature rule
2. methods rule
3. properties rule
9
Signature Rule
• Every call that is type-correct with the supertype 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

10
Signature Rule in Java
1. Subtype’s method can have fewer exceptions
but NOT throw more exceptions
2. Arguments and return type should be identical:
(stricter than necessary)

Foo clone();
Foo x = y.clone();
Object clone();
Foo x = (Foo) y.clone();
1. Enforced by the compiler at compile-time
11
NonEmptySet: Remove
public class NonEmptySet extends IntSet {
Violates signature rule
…
– will not compile
public void remove(int x) throws
EmptySetException {
// EFFECTS: If set has at least two elements,
// then remove x
// Otherwise, throw the EmptySetException
….
}
}
12
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
….
}
}
13
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 ?)

14
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
15
Methods rule
• A sub-type method can weaken the precondition (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
16
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, subtype 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)
17
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 ?
18
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
19
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
….
}

20
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
…
}

21
What happens in this code ?
public static void findMax (NonEmptySet s) {
int max = s.choose();
Can throw an
iterator g = s.elements();
exception if IntSet is
passed in as argument
while (g.hasNext() ) {
…
}
}
22
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
23
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
24
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.
25
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
26
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(Integer i) {
addCount++;
return super.add(i);
}
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 subtype 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: Composition1
public class InstrumentedIntSet implements Set
{
private IntSet s;
private int addCount;
public InstrumentedIntSet( ) {
addCount = 0;
s = new IntSet();
}
InstrumentedIntSet: Composition2
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 ?
Start

Do we
need to
use B in
place of
A?

NO

YES
Does B
satisfy
the
LSP ?

NO

YES
Make B a sub-type of A,
but try to use the public
interface of A in B

Do B and
A need to
share any
code ?
YES
Make B contain an
object of type A
(common interface
if necessary)

NO
Make B and A
independent
types (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 ?
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

Weitere ähnliche Inhalte

Was ist angesagt?

The Awesome Python Class Part-3
The Awesome Python Class Part-3The Awesome Python Class Part-3
The Awesome Python Class Part-3Binay Kumar Ray
 
The Awesome Python Class Part-4
The Awesome Python Class Part-4The Awesome Python Class Part-4
The Awesome Python Class Part-4Binay Kumar Ray
 
Super and final in java
Super and final in javaSuper and final in java
Super and final in javaanshu_atri
 
The Awesome Python Class Part-5
The Awesome Python Class Part-5The Awesome Python Class Part-5
The Awesome Python Class Part-5Binay Kumar Ray
 
Spinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment CommunicationSpinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment CommunicationCITSimon
 

Was ist angesagt? (6)

The Awesome Python Class Part-3
The Awesome Python Class Part-3The Awesome Python Class Part-3
The Awesome Python Class Part-3
 
The Awesome Python Class Part-4
The Awesome Python Class Part-4The Awesome Python Class Part-4
The Awesome Python Class Part-4
 
Super and final in java
Super and final in javaSuper and final in java
Super and final in java
 
The Awesome Python Class Part-5
The Awesome Python Class Part-5The Awesome Python Class Part-5
The Awesome Python Class Part-5
 
Spinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment CommunicationSpinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment Communication
 
Java chapter 3
Java chapter 3Java chapter 3
Java chapter 3
 

Ähnlich wie Typehierarchy

note2_DesignPatterns (1).pptx
note2_DesignPatterns (1).pptxnote2_DesignPatterns (1).pptx
note2_DesignPatterns (1).pptxReemaAsker1
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave ImplicitMartin Odersky
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptSanthosh Kumar Srinivasan
 
The maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID PrinciplesThe maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID PrinciplesMuhammad Raza
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.pptYonas D. Ebren
 
Style & Design Principles 02 - Design Patterns
Style & Design Principles 02 - Design PatternsStyle & Design Principles 02 - Design Patterns
Style & Design Principles 02 - Design PatternsNick Pruehs
 
Fuzzy logic
Fuzzy logicFuzzy logic
Fuzzy logicAdPatel5
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaSandesh Sharma
 
principles of object oriented class design
principles of object oriented class designprinciples of object oriented class design
principles of object oriented class designNeetu Mishra
 

Ähnlich wie Typehierarchy (20)

note2_DesignPatterns (1).pptx
note2_DesignPatterns (1).pptxnote2_DesignPatterns (1).pptx
note2_DesignPatterns (1).pptx
 
Design for Testability
Design for TestabilityDesign for Testability
Design for Testability
 
L04 Software Design 2
L04 Software Design 2L04 Software Design 2
L04 Software Design 2
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in Javascript
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
The maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID PrinciplesThe maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID Principles
 
Design Patterns - GOF
Design Patterns - GOFDesign Patterns - GOF
Design Patterns - GOF
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
 
Style & Design Principles 02 - Design Patterns
Style & Design Principles 02 - Design PatternsStyle & Design Principles 02 - Design Patterns
Style & Design Principles 02 - Design Patterns
 
Fuzzy logic
Fuzzy logicFuzzy logic
Fuzzy logic
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
Oops
OopsOops
Oops
 
30csharp
30csharp30csharp
30csharp
 
30c
30c30c
30c
 
principles of object oriented class design
principles of object oriented class designprinciples of object oriented class design
principles of object oriented class design
 
Inheritance
InheritanceInheritance
Inheritance
 
Design patterns
Design patternsDesign patterns
Design patterns
 
L5
L5L5
L5
 

Kürzlich hochgeladen

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 

Kürzlich hochgeladen (20)

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 

Typehierarchy

  • 1. EECE 210: Software Design Type Hierarchies and the Substitution Principle
  • 2. Objectives • Apply the Liskov Substitution Principle (LSP) to the design of type hierarchies • Use abstract base classes to solve LSP problem • Decide when to use composition over inheritance
  • 3. 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
  • 4. 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 4
  • 5. 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 …. } } 5
  • 6. 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; } 6
  • 7. Usage of removeAny IntSet s = new IntSet(); … // Add elements to s while ( removeAny(s) ) { … } // s is empty at this point 7
  • 8. 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 ! 8
  • 9. 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: 1. signature rule 2. methods rule 3. properties rule 9
  • 10. Signature Rule • Every call that is type-correct with the supertype 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 10
  • 11. Signature Rule in Java 1. Subtype’s method can have fewer exceptions but NOT throw more exceptions 2. Arguments and return type should be identical: (stricter than necessary) Foo clone(); Foo x = y.clone(); Object clone(); Foo x = (Foo) y.clone(); 1. Enforced by the compiler at compile-time 11
  • 12. NonEmptySet: Remove public class NonEmptySet extends IntSet { Violates signature rule … – will not compile public void remove(int x) throws EmptySetException { // EFFECTS: If set has at least two elements, // then remove x // Otherwise, throw the EmptySetException …. } } 12
  • 13. 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 …. } } 13
  • 14. 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 ?) 14
  • 15. 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 15
  • 16. Methods rule • A sub-type method can weaken the precondition (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 16
  • 17. 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, subtype 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) 17
  • 18. 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 ? 18
  • 19. 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 19
  • 20. 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 …. } 20
  • 21. 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 … } 21
  • 22. What happens in this code ? public static void findMax (NonEmptySet s) { int max = s.choose(); Can throw an iterator g = s.elements(); exception if IntSet is passed in as argument while (g.hasNext() ) { … } } 22
  • 23. 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 23
  • 24. 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 24
  • 25. 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. 25
  • 26. 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 26
  • 27. Group Activity • In the handout
  • 28. 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
  • 29. 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)
  • 30. 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
  • 31. 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;} }
  • 32. 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
  • 33. 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); } }
  • 34. 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) );
  • 35. 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.
  • 36. 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 ?
  • 37. 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();
  • 38. 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
  • 39. Abstract Classes Vs. Interfaces
  • 40. Class Exercise • Distributed as a handout in class
  • 41. 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
  • 42. 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() ); } }
  • 43. 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
  • 44. InstrumentedIntSet: Inheritance public class InstrumentedIntSet extends IntSet { private int addCount; // The number of attempted element insertions public InstrumentedIntSet() { super(); addCount = 0; } public boolean add(Integer i) { addCount++; return super.add(i); } public boolean addAll(Collection<int> c) { addCount += c.size(); return super.addAll(c); } public int getAddCount() { return addCount; }
  • 45. 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)
  • 46. Solution: Use Composition • Instead of making InstrumentedIntSet a subtype 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
  • 47. InstrumentedIntSet: Composition1 public class InstrumentedIntSet implements Set { private IntSet s; private int addCount; public InstrumentedIntSet( ) { addCount = 0; s = new IntSet(); }
  • 48. InstrumentedIntSet: Composition2 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 ); }
  • 49. Should B be a subtype of A ? Start Do we need to use B in place of A? NO YES Does B satisfy the LSP ? NO YES Make B a sub-type of A, but try to use the public interface of A in B Do B and A need to share any code ? YES Make B contain an object of type A (common interface if necessary) NO Make B and A independent types (common interface if necessary)
  • 50. 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 ?
  • 51. 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

Hinweis der Redaktion

  1. 1. The code should behave the same way a supertype would have even when subtype is used
  2. Subtypes can have fewer exceptions Enforced by the compiler