Type Abstraction Liskov, Chapter 7. 2 Liskov Substitution Principle In any client code, if the supertype object is substituted by a subtype object, the.

Slides:



Advertisements
Similar presentations
1 Refactoring with Contracts Shmuel Tyszberowicz School of Computer Science The Academic College of Tel Aviv Yaffo Maayan Goldstein School of Computer.
Advertisements

Identity and Equality Based on material by Michael Ernst, University of Washington.
The Substitution Principle SWE 332 – Fall Liskov Substitution Principle In any client code, if subtype object is substituted for supertype object,
Data Abstraction II SWE 619 Software Construction Last Modified, Spring 2009 Paul Ammann.
5/17/2015 OO Design: Liskov Substitution Principle 1.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Recommendation: Play the game and attempt to answer the questions yourself without looking at the answers. You’ll learn much less if you just look at the.
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.
Specifications Liskov Chapter 9 SWE 619 Last Updated Fall 2008.
Ranga Rodrigo. Class is central to object oriented programming.
Procedure specifications CSE 331. Outline Satisfying a specification; substitutability Stronger and weaker specifications - Comparing by hand - Comparing.
1 Abstraction  Identify important aspects and ignore the details  Permeates software development programming languages are abstractions built on hardware.
Cs205: engineering software university of virginia fall 2006 Data Abstraction David Evans
Effective Java: Generics Last Updated: Spring 2009.
Object-oriented Programming in Java. What is OOP?  The goal is (subtype) polymorphism  Achieved by Classes (user-defined types) Classes (user-defined.
EECE 310: Software Engineering Iteration Abstraction.
Effective C#, Chapter 1: C# Language Elements Last Updated: Fall 2011.
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.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 12: Subtyping Rules What’s the.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
Types in programming languages1 What are types, and why do we need them?
David Evans CS655: Programming Languages University of Virginia Computer Science Lecture 17: Inheritance & Behavioral.
Cs205: engineering software university of virginia fall 2006 David Evans Substitution Principle.
Data Abstractions EECE 310: Software Engineering.
Type Abstraction SWE Spring October 05Kaushik, Ammann Substitution Principle “In any client code, if supertype object is substituted.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Polymorphism Liskov 8. Outline equals() Revisiting Liskov’s mutable vs. not rule Polymorphism Uniform methods for different types “easy” polymorphism.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Data Abstraction SWE 619 Software Construction Last Modified, Spring 2009 Paul Ammann.
Ceg860 (Prasad)L17IT1 Inheritance Techniques Subcontracting Anchored Types.
Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.
PROGRAMMING PRE- AND POSTCONDITIONS, INVARIANTS AND METHOD CONTRACTS B MODULE 2: SOFTWARE SYSTEMS 13 NOVEMBER 2013.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
Polymorphism SWE 619. Outline equals() Revisiting Liskov’s mutable vs. not rule Polymorphism Uniform methods for different types “easy” polymorphism Element.
CSSE501 Object-Oriented Development. Chapter 10: Subclasses and Subtypes  In this chapter we will explore the relationships between the two concepts.
Iteration Abstraction SWE Software Construction Fall 2009.
FEN 2014UCN Teknologi/act2learn1 Object-Oriented Programming “ The Three Pillars of OOP”: Encapsulation Inheritance Polymorphism The Substitution Principle.
Cs2220: Engineering Software Class 12: Substitution Principle Fall 2010 University of Virginia David Evans.
Cs2220: Engineering Software Class 13: Behavioral Subtyping Fall 2010 University of Virginia David Evans.
Zach Tatlock / Winter 2016 CSE 331 Software Design and Implementation Lecture 13 Generics 1.
Type Hierarchies. Type Hieararchy Why?: Want to define family of related types. At the top of the hierarchy, a type whose spec defines behavior common.
619 Final Review Last updated Fall 2011 Paul Ammann.
Recitation 7 Godfrey Tan March 21, Administrivia PS6 due Tuesday right after break Final Project descriptions will be handed out Monday after break.
Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle.
Reasoning and Design (and Assertions). How to Design Your Code The hard way: Just start coding. When something doesn’t work, code some more! The easier.
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
EECE 310: Software Engineering
Object-oriented Programming in Java
Inheritance and Polymorphism
Adaptive Code Via C#
Specifications Liskov Chapter 9
CSE 331 Subtyping slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
EECE 310: Software Engineering
Type Abstraction SWE Spring 2009.
Subtype Polymorphism, Subtyping vs
Iteration Abstraction
Subtyping Rules David Evans cs205: engineering software BlackBear
Type Abstraction Liskov, Chapter 7.
Iteration Abstraction
SWE 619 Software Construction Last Modified, Fall 2015 Paul Ammann
Lecture 4: Data Abstraction CS201j: Engineering Software
EECE 310: Software Engineering
619 Final Review Last updated Spring 2010 © : Paul Ammann.
619 Final Review Fall 2017 Professor Ammann.
Assertions References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 4/25/2019.
Lecture 13: Subtyping Rules Killer Bear Climber
Type Abstraction SWE Spring 2013.
Presentation transcript:

Type Abstraction Liskov, Chapter 7

2 Liskov Substitution Principle In any client code, if the supertype object is substituted by a subtype object, the client’s expectations will still be satisfied. Everyone learns this in intro OO courses, but this is a lot harder than it looks.

3 Why do we subtype? Extended Behavior Standard “Is-A” Relationships Multiple implementations SparsePoly, DensePoly Different implementations Same specifications All supertype behavior must be supported No extra stuff!

4 Extended behavior Extended Behavior Specialize the behavior of supertype Classic ‘IS A’ relationship Usually has additional rep. Vehicle Car Bike Constraint View: for contracts CAR Object View: for rep Vehicle

5 Conflict in two goals? Poly SparsePolyLogPolyDensePoly Poly SparsePoly LogPoly DensePoly LogPoly: Extends the behavior of Poly by keeping track of how many times it was accessed by the calling code. It has additional rep (a log of accesses)

6 Dispatching Object[] x = new Object[2]; x[0] = new String(“abc”); x[1] = new Integer(1); for(int i=0; i<x.length;i++) System.out.println(x[i].toString()); Compiler does not complain Which toString() method is called? Object.toString(), String.toString() or Integer.toString()? At run time, “best fit” code is called.

7 MaxIntSet Example (Fig 7.5) public class MaxIntSet extends IntSet { private int biggest; // biggest element of set if not empty public MaxIntSet {super (); } //Why call super() ??? public void insert (int x) { if (size() == 0 || x > biggest) biggest = x; super.insert(x); } public int max () throws EmptyException { if (size() == 0) throw new EmptyException (“MaxIS.max”); return biggest; }

8 MaxIntSet.remove() public void remove (int x) { super.remove(x); if (size()==0 || x <biggest) return; Iterator g = elements(); biggest = ((Integer) g.next()).intValue(); while (g.hasNext() { int z = ((Integer) g.next()).intValue(); if (z>biggest) biggest = z; } Need to call supertype’s remove functionality. (private rep!) Must maintain subtype’s rep invariant

9 MaxIntSet Abstract State // Overview: MaxIntSet is a subtype of IntSet with an additional // method, max, to determine the maximum element of the set Two possible abstract states: {x1, x2,... xN} - same as IntSet - visible abstract state Which one to choose? Design decision - either is possible Second may seem more natural, but there are significant advantages to the first. We will revisit this via Bloch later in the semester.

10 MaxIntSet.repOk() public boolean repOk() { if (!super.repOk()) return false; if (size() == 0) return true; boolean found = false; Iterator g = elements(); while(g.hasNext()) { int z = ((Integer)g.next()).intValue(); if (z>biggest) return false; if (z==biggest) found = true; return found; }

11 repOk() and Dynamic Dispatching public class IntSet { public void insert(int x) {...; repOk();} public void remove(int x) {...; repOk();} // where to? public boolean repOk() {...} } public class MaxIntSet extends IntSet { public void insert(int x) {...; super.insert(x); repOk();} public void remove(int x) {super.remove(x);...; repOk();} public boolean repOk() {super.repOk();...;} } MaxIntSet s = {3, 5}; s.remove(5); // repOk()????

12 Meaning of subtypes Subtypes behavior must support supertype behavior – (SP) In particular following three properties: 1. Signature Rule 2. Methods Rule 3. Properties Rule

13 Signature Rule Subtypes must have all methods of supertype Signatures of methods must be compatible with supertype signature Return types identical; Covariant after Java 1.5 Guaranteed by Java compiler Caution: Overriding vs. overloading public boolean equals(Foo foo) {...} public boolean equals(Object foo) {...} Exceptions Signature Rule allows Subtype to throw fewer But methods rule must be satisfied

14 Methods Rule When object belongs to subtype, subtype method is called We must still be able to reason about these methods using supertype specs Suppose SortedIntSet extends IntSet IntSet x = new IntSet(); IntSet y = new SortedIntSet(); x.insert(3); //What is this_post? y.insert(3); //What is this_post?

15 Methods Rule 1. Cannot take away methods! 1. Subtype API should atleast be equal or greater than supertype API 2. Must maintain the contract! 1. Precondition rule: What can a subclass do with preconditions in supertype spec? 2. Post condition rule: What can a subclass do with postconditions in supertype spec?

16 Precondition rule Subtype is allowed to weaken the precondition! Formally: pre_super |- pre_sub Super //Requires: x > 5 Case 1: Sub //Requires x > 6 Case 2: Sub // Requires x > 4 x>5  x>4?Which is weaker? x>5  x>6? Not checked by compiler

17 Post condition rule Informally, subtype is allowed to strengthen the post condition Formally: pre_super && post_sub |- post_super Super: // Effects: returns y < 5 Sub: //Effects: returns y < 4 Sub: //Effects: returns y < 6 Which one is a stronger condition?

18 Same Diagram as Method Verification SuperType Method Contract Subtype Method Contract AF() Supertype State (Post-Super)Supertype State (Pre-Super) Subtype State (Post-Sub) Subtype State (Pre-Sub) ?

19 Examples Super public void addZero() //pre: this is not empty //post: add zero to this public void addZero() throws ISE //pre: this is not empty //post: add zero to this Sub public void addZero() //post: add zero to this public void addZero() throws ISE //post: if this is empty, throw ISE else add zero to this Satisfies Signature and Method rules Satisfies Signature and Method rules

20 More examples Super public void addZero() //pre: this is not empty //post: add zero to this public void addZero() throws ISE //post: if this is empty, throws ISE // else add zero to this Sub public void addZero() throws ISE //post: add zero to this public void addZero() //post: add zero to this Does not satisfy Signature rule Does not satisfy Postcondition part of methods rule

21 A Java Example What may subtypes of Iterator do?Iterator

22 Client code private void foo { … try{ o.addZero(); } (catch EE){ //do something: Client expects to get here! }

23 Methods rule vs. Properties rule Methods rule is for single method invocation Properties rule about abstract objects. Invariants: E.g. IntSets do not contain duplicates s.isIn(x) following s.remove(x) always false Evolution properties: E.g. MonotoneSets only grow (no remove method allowed).

24 Liskov 7.8, 7.9, 7.10 public class Counter{ // Liskov 7.8 public Counter() //EFF: Makes this contain 0 public int get() //EFF: Returns the value of this public void incr() //MOD: this //EFF: Increments value of this } public class Counter2 extends Counter { // Liskov 7.9 public Counter2() //EFF: Makes this contain 0 public void incr() // MOD: this //EFF: double this } public class Counter3 extends Counter { // Liskov 7.10 public Counter3(int n) //EFF: Makes this contain n public void incr(int n) // MOD: this //EFF: if n>0 add n to this }

25 Anaylsis Signature rule: Careful with over- load vs. ride Counter2 ok? Counter3 ok? Methods rule: Precondition rule: Counter 2 ok? Counter 3 ok? Postcondition rule: Counter 2 ok? Counter 3 ok?

26 More About Properties Rule Collection c =...; c.add (“cat”); c.remove(“cat”); // consider the following observer call: // What is behavior if c is a Set? // What is behavior if c is a Bag? if (c.contains(“cat”) {... } // Such “algebraic” relations are extremely useful for testing