Principles of Object-Oriented Design

Similar documents
SOLID: Principles of OOD

Bruno Bossola SOLID Design Principles

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

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

OO Class Design Principles

! Needles Complexity! make design more general than needed " e.g. interfaces and/or abstract classes with just one implementor

S.O.L.I.D. Principles of

Highlights of Previous Lecture

! Needles Complexity! make design more general than needed " e.g. interfaces and/or abstract classes with just one implementor

Principles of OO Design

Open Closed Principle (OCP)

Inheritance and object compatibility

17.11 Bean Rules persistent

Lecture: Modular Design

Common mistakes and Basic Design Principles. David Rabinowitz

Ingegneria del Software Corso di Laurea in Informatica per il Management. Software quality and Object Oriented Principles

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

Principles of Object-Oriented Design

Liskov Substitution Principle

Design Principles: Part 2

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

Design Principles: Part 2

Software Engineering

Object Oriented Software Design - I

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

11/2/09. Code Critique. What goal are we designing to? What is the typical fix for code smells? Refactoring Liskov Substitution Principle

Intro to: Design Principles

Component-Level Design

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

Stability. Introduction

Expanding Our Horizons. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 9 09/25/2011

Object-Oriented Design

Object Fundamentals Part Three. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 4 09/06/2007

Object-oriented design principles

Object design. François Schwarzentruber ENS Cachan Antenne de Bretagne

11/4/15. Review. Objec&ves. Refactoring for Readability. Review. Liskov Subs&tu&on Principle (LSP) LISKOV SUBSTITUTION PRINCIPLE

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

Inheritance and Substitution (Budd chapter 8, 10)

Inheritance, Polymorphism, and Interfaces

CS 520 Theory and Practice of Software Engineering Fall 2018

Object-Oriented Design

COURSE 2 DESIGN PATTERNS

1 Introduction 2 Complex Systems 3 Object Model 4 Dependency Management 5 Class Design. Object Oriented Programming in Physics

OO Design Principles

Object design. François Schwarzentruber ENS Cachan Antenne de Bretagne

Introduction to Object-Oriented Programming

Software Engineering I (02161)

Today's Agenda. References. Open Closed Principle. CS 247: Software Engineering Principles. Object-Oriented Design Principles

Summary of the course lectures

SOLID Principles. Equuleus Technologies. Optional Subheading October 19, 2016

Programming in the large

Abstraction. Design fundamentals in OO Systems. Fundamental Software Development Principles

Plan. Design principles: laughing in the face of change. What kind of change? What are we trying to achieve?

The Liskov Substitution Principle

1.00 Lecture 14. Exercise: Plants

Polymorphism and Inheritance

CSC207H: Software Design SOLID. CSC207 Winter 2018

CS 520 Theory and Practice of Software Engineering Fall 2017

CSC Advanced Object Oriented Programming, Spring Specification

Design by Contract in Eiffel

More on Inheritance. Interfaces & Abstract Classes

Type Hierarchy. Lecture 6: OOP, autumn 2003

Chapter 8: Class and Method Design

Object-Oriented Concepts and Design Principles

Chapter 5 Object-Oriented Programming

Object-Oriented Design II

MORE OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 4 09/01/2011

Exam in TDDB84: Design Patterns,

First IS-A Relationship: Inheritance

Objec&ves. Review. Liskov Subs&tu&on Principle Refactoring for Extensibility. What are reasons that we refactor our code?

More on object orientation

Classes and Objects. Object Orientated Analysis and Design. Benjamin Kenwright

CS 320 Introduction to Software Engineering Spring March 06, 2017

Eliminate enterprise software design instability - protect variations! Nickolay Kofanov

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

Introduction to Computation and Problem Solving

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Welcome to Design Patterns! For syllabus, course specifics, assignments, etc., please see Canvas

CSC207 Week 3. Larry Zhang

Object Relationships

More OO Fundamentals. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 4 09/11/2012

Object-Oriented Design

CSE 70 Final Exam Fall 2009

Fortgeschrittene objektorientierte Programmierung (Advanced Object-Oriented Programming)

More Relationships Between Classes

Outline. Software Rots

Test Code Patterns. How to design your test code

Originality is Overrated: OO Design Principles

Single Responsibility Principle (SRP)

Object- Oriented Design with UML and Java Part I: Fundamentals

6.170 Recitation #5: Subtypes and Inheritance

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

Principles of Software Construction: Objects, Design, and Concurrency. Assigning Responsibilities to Objects. toad. Jonathan Aldrich Charlie Garrod

Conformance. Object-Oriented Programming Spring 2015

Introduction to Object-Oriented Programming

Java Object Oriented Design. CSC207 Fall 2014

Inheritance (Chapter 7)

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Transcription:

Principles of Object-Oriented Design 1

The Object-Oriented... Hype What are object-oriented (OO) methods? OO methods provide a set of techniques for analysing, decomposing, and modularising software system architectures In general, OO methods are characterized by structuring the system architecture on the basis of its objects (and classes of objects) rather than the actions it performs What is the rationale for using OO? In general, systems evolve and functionality changes, but objects and classes tend to remain stable over time Use it for large systems Use it for systems that change often 2

OO Design vs. OO Programming Object-Oriented Design a method for decomposing software architectures based on the objects every system or subsystem manipulates relatively independent of the programming language used Object-Oriented Programming construction of software systems as Structured collection of Abstract Data Types (ADT) Inheritance Polymorphism concerned with programming languages and implementation issues 3

Polymorphism Behavior promised in the public interface of superclass objects implemented by subclass objects in the specific way required for the subclass Why Is this Important? Allow subclasses to be treated like instances of their superclasses Flexible architectures and designs high-level logic defined in terms of abstract interfaces relying on the specific implementation provided by subclasses subclasses can be added without changing high-level logic 4

Polymorphism Example 5

Signs of Rotting Design Rigidity code difficult to change (Continuity) management reluctance to change anything becomes policy Fragility even small changes can cause cascading effects code breaks in unexpected places (Protection) Immobility code is so tangled that it's impossible to reuse anything Composability Viscosity much easier to hack than to preserve original design 6

Causes of Rotting Design Changing Requirements is inevitable "All systems change during their life-cycles. This must be borne in mind when developing systems expected to last longer than the first version". (I. Jacobson, OOSE, 1992) Dependency Management the issue of coupling and cohesion It can be controlled! create dependency firewalls see DIP example 7

Open-Closed Principle (OCP) "Software Systems change during their life time" both better designs and poor designs have to face the changes; good designs are stable Software entities should be open for extension, but closed for modification B. Meyer, 1988 / quoted by R. Martin, 1996 Be open for extension module's behavior can be extended Be closed for modification source code for the module must not be changes Modules should be written so they can be extended without requiring them to be modified 8

Open the door... How to make the Car run efficiently with a TurboEngine? Only by changing the Car!...in the given design 9

... But Keep It Closed! A class must not depend on a concrete class! It must depend on an abstract class......using polymorphic dependencies (calls) 10

Strategic Closure "No significant program can be 100% closed " R.Martin, The Open-Closed Principle, 1996 Closure not complete but strategic Use abstraction to gain explicit closure provide class methods which can be dynamically invoked to determine general policy decisions e.g. draw Squares before Circles design using abstract ancestor classes Use "Data-Driven" approach to achieve closure place volatile policy decisions in a separate location e.g. a file or a separate object minimizes future change locations 11

OCP Heuristics Make all object-data private No Global Variables! Changes to public data are always at risk to open the module They may have a rippling effect requiring changes at many unexpected locations; Errors can be difficult to completely find and fix. Fixes may cause errors elsewhere. Non-private members are modifiable Case 1: "I swear it will not change" may change the status of the class Case 2: the Time class may result in inconsistent times 12

OCP Heuristics (2) RTTI is Ugly and Dangerous! RTTI is ugly and dangerous If a module tries to dynamically cast a base class pointer to several derived classes, any time you extend the inheritance hierarchy, you need to change the module recognize them by type switch-es or if-else-if structures Not all these situations violate OCP all the time when used only as a "filter" 13

Liskov Substitution Principle (LSP) The key of OCP: Abstraction and Polymorphism Implemented by inheritance How do we measure the quality of inheritance? Inheritance should ensure that any property proved about supertype objects also holds for subtype objects B. Liskov, 1987 Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it. R. Martin, 1996 14

Inheritance Appears Simple class Bird { public: virtual void fly(); // Bird can fly }; // has beak, wings,... class Parrot : public Bird { // Parrot is a bird public: virtual void mimic(); // Can Repeat words... }; //... Parrot mypet; mypet.mimic(); // my pet being a parrot can Mimic() mypet.fly(); // my pet is-a bird, can fly 15

Penguins Fail to Fly! class Penguin : public Bird { public: void fly() { error ( Penguins don t fly! ); } }; void PlayWithBird (Bird& abird) { abird.fly(); // OK if Parrot. } // if bird happens to be Penguin...OOOPS!! Does not model: Penguins can t fly It models Penguins may fly, but if they try it is error Run-time error if attempt to fly not desirable Think about Substitutability - Fails LSP 16

Design by Contract Advertised Behavior of an object: advertised Requirements (Preconditions) advertised Promises (Postconditions) When redefining a method in a derivate class, you may only replace its precondition by a weaker one, and its postcondition by a stronger one B. Meyer, 1988 Derived class services should requireno more and promise no less int Base::f(int x); // REQUIRE: x is odd // PROMISE: return even int int Derived::f(int x); // REQUIRE: x is int // PROMISE: return 8 17

Square IS-A Rectangle? Square? Should I inherit Square from Rectangle? 18

The Answer is... Override setheight and setwidth duplicated code... static binding (in C++) void f(rectangle& r) { r.setheight(5); } change base class to set methods virtual The real problem void g(rectangle& r) { r.setwidth(5); r.setheight(4); } // How large is the area? 20!... Are you sure? ;-) IS-A relationship must refer to the behavior of the class! 19

LSP is about Semantics and Replacement The meaning and purpose of every method and class must be clearly documented Lack of user understanding will induce de facto violations of LSP Replaceability is crucial Whenever any class is referenced by any code in any system, any future or existing subclasses of that class must be 100% replaceable Because, sooner or later, someone will substitute a subclass; it s almost inevitable. 20

LSP and Replaceability Any code which can legally call another class s methods must be able to substitute any subclass of that class without modification: Client Service Class Client Service Class Unexpected Subclass 21

LSP Related Heuristic (2) It is illegal for a derived class, to override a base-class method with a NOP method NOP = a method that does nothing Solution 1: Inverse Inheritance Relation if the initial base-class has only additional behavior e.g. Dog - DogNoWag Solution 2: Extract Common Base-Class if both initial and derived classes have different behaviors for Penguins Birds, FlyingBirds, Penguins Classes with bad state e.g. stupid or paralyzed dogs... 22

Example of Rigidity and Immobility Read Keyboard Copy Write Disk Write Printer enum OutputDevice {printer, disk}; void Copy(OutputDevice dev){ } int c; while((c = ReadKeyboard())!= EOF) if(dev == printer) else WritePrinter(c); WriteDisk(c); void Copy(){ int c; while ((c = ReadKeyboard())!= EOF) WritePrinter(c); } 23

Dependency Inversion Principle I. High-level modules should not depend on low-level modules. Both should depend on abstractions. II. Abstractions should not depend on details. Details should depend on abstractions OCP states the goal; DIP states the mechanism R. Martin, 1996 A base class in an inheritance hierarchy should not know any of its subclasses Modules with detailed implementations are not depended upon, but depend themselves upon abstractions 24

Procedural vs. OO Architecture Procedural Architecture Object-Oriented Architecture 25

Copy DIP Applied on Example class Reader { public: virtual int read()=0; }; Reader Writer class Writer { public: virtual void write(int)=0; }; Keyboard Reader Printer Writer Disk Writer void Copy(Reader& r, Writer& w){ int c; while((c = r.read())!= EOF) w.write(c); } 26

DIP Related Heuristic Design to an interface, not an implementation! Use inheritance to avoid direct bindings to classes: Interface (abstract class) Client Implementation (concrete class) 27

Design to an Interface Abstract classes/interfaces: tend to change much less frequently abstractions are hinge points where it is easier to extend/modify shouldn t have to modify classes/interfaces that represent the abstraction (OCP) Exceptions Some classes are very unlikely to change; therefore little benefit to inserting abstraction layer Example: String class In cases like this can use concrete class directly as in Java or C++ 28

DIP Related Heuristic Avoid Transitive Dependencies Avoid structures in which higher-level layers depend on lowerlevel abstractions: In example below, Policy layer is ultimately dependant on Utility layer. Policy Layer Depends on Mechanism Layer Depends on Utility Layer 29

Solution to Transitive Dependencies Use inheritance and abstract ancestor classes to effectively eliminate transitive dependencies: Policy Layer depends on Mechanism Interface Mechanism Layer depends on Utility Interface Utility Layer 30

DIP - Related Heuristic When in doubt, add a level of indirection If you cannot find a satisfactory solution for the class you are designing, try delegating responsibility to one or more classes: Problem Holder Problem Solver 31

When in doubt... It is generally easier to remove or by-pass existing levels of indirection than it is to add them later: Blue class s indirect message calls to red class fail to meet some criteria (e.g. real-time constraints, etc.) So, Blue class re-implements some or all of green class s responsibilities for efficiency and calls red object directly X 32

The Founding Principles The three principles are closely related Violating either LSP or DIP invariably results in violating OCP LSP violations are latent violations of OCP It is important to keep in mind these principles to get most out of OO development...... and go beyond buzzwords and hype ;) 33