Principles of Object-Oriented Design SEI, SJTU WEB APPS and SERVICES.

Slides:



Advertisements
Similar presentations
Understand and appreciate Object Oriented Programming (OOP) Objects are self-contained modules or subroutines that contain data as well as the functions.
Advertisements

1 Object-Oriented Reengineering © R. Marinescu Lecture 5 Radu Marinescu Principles of Object-Oriented Design.
General OO Concepts and Principles CSE301 University of Sunderland Harry R. Erwin, PhD.
Lecture 9 Improving Software Design CSC301-Winter 2011 – University of Toronto – Department of Computer Science Hesam C. Esfahani
SOLID Object Oriented Design Craig Berntson
Inheritance and object compatibility Object type compatibility An instance of a subclass can be used instead of an instance of the superclass, but not.
Common mistakes Basic Design Principles David Rabinowitz.
Common mistakes Basic Design Principles Amit Shabtay.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Chapter 10 Classes Continued
3/15/05H-1 © 2001 T. Horton CS 494 Object-Oriented Analysis & Design Evaluating Class Diagrams Topics include: Cohesion, Coupling Law of Demeter (handout)
CSCI-383 Object-Oriented Programming & Design Lecture 15.
CSc 335: Three More OO Design Principles
TEST-1 7. Object-Oriented Design Principles. TEST-2 The Pillars of the Paradigm Abstraction Encapsulation Hierarchy –Association, Aggregation –Inheritance.
1 OO Design Principles Project Group eXtreme Programming Md. Abul Bashar 07/09/2004.
Chapter 12: Adding Functionality to Your Classes.
Object-oriented metrics Design decisions: Class Cohesion Open-Closed Single Responsibility Interface Segregation Dependency Inversion Liskov Substitution.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CLASS DESIGN PRINCIPLES Lecture 2. The quality of the architecture What is a good design? It is the design that at least does not have signs of “bad”.
Lecture 9 Polymorphism Richard Gesick.
1 OO Design Novosoft, 2001 by V. Mukhortov. 2 OO Design Goals  Flexibility Changes must be localized  Maintainability Modules requiring changes can.
Ceg860 (Prasad)L6MR1 Modularity Extendibility Reusability.
1 Abstraction  Identify important aspects and ignore the details  Permeates software development programming languages are abstractions built on hardware.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Company Confidential – Do Not Duplicate 2 Copyright 2008 McLane Advanced Technologies, LLC S.O.L.I.D. Software Development Achieving Object Oriented Principles,
OODP Prudent OO Design. OODP-2 The Pillars of the Paradigm Abstraction Encapsulation Hierarchy –Association, Aggregation –Inheritance Polymorphism.
© 2004 Capgemini - All rights reserved SOLID - OO DESIGN PRINCIPLES Andreas Enbohm, Capgemini.
CSCI 383 Object-Oriented Programming & Design Lecture 17 Martin van Bommel.
1 Computer Science 340 Software Design & Testing Inheritance.
SWE © Solomon Seifu ELABORATION. SWE © Solomon Seifu Lesson 12-5 Software Engineering Design Goals.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Design Principles iwongu at gmail dot com.
The benefits of SOLID in software development Ruben Agudo Santos (GS-AIS-HR)
Software Design Principles
1 Single Responsibility Principle Open Closed Principle Liskov Substitution Principle Law of Demeter CSC 335: Object-Oriented Programming and Design.
Object Oriented Software Development
Incremental Design Why incremental design? Goal of incremental design Tools for incremental design  UML diagrams  Design principles  Design patterns.
Elements of OO Abstraction Encapsulation Modularity Hierarchy: Inheritance & Aggregation 4 major/essential elements3 minor/helpful elements Typing Concurrency.
OO Design Principles Copyright © Vyacheslav Mukhortov, Nikita Nyanchuk-Tatarskiy, Copyright © INTEKS LLC,
Software Design Patterns Curtsy: Fahad Hassan (TxLabs)
Object-Oriented Programming Chapter Chapter
(1) ICS 313: Programming Language Theory Chapter 12: Object Oriented Programming.
Object Oriented Programming
CPS Inheritance and the Yahtzee program l In version of Yahtzee given previously, scorecard.h held information about every score-card entry, e.g.,
1 Design by Principles (Robert Martin) Software Engineering.
Evaluating an Object-Oriented Design ©SoftMoore ConsultingSlide 1.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CSSE501 Object-Oriented Development. Chapter 10: Subclasses and Subtypes  In this chapter we will explore the relationships between the two concepts.
SOLID Design Principles
Overview of C++ Polymorphism
S.Ducasse Stéphane Ducasse 1 Some Principles Stéphane Ducasse ---
 2006 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle.
3/1/01H-1 © 2001 T. Horton CS 494 Object-Oriented Analysis & Design Evaluating Class Diagrams Topics include: Cohesion, Coupling Law of Demeter (handout)
CSCI-383 Object-Oriented Programming & Design Lecture 17.
CSCE 240 – Intro to Software Engineering Lecture 3.
NCCUCS Software Engineering 補充投影片 April 14, 2014.
CSCI 383 Object-Oriented Programming & Design Lecture 15 Martin van Bommel.
14 Jul 2005CSE403, Summer'05, Lecture 09 Lecture 09: Fundamental Principles and Best Practices for Software Design Valentin Razmov.
1 Advanced Object- oriented Design – Principles CS320 Fall 2005.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Software Design Principles
Inheritance and Polymorphism
Copyright © by Curt Hill
Software Design Principles
Subtype Polymorphism, Subtyping vs
Principles of Object-Oriented Design
Principles of Object-Oriented Design
Presentation transcript:

Principles of Object-Oriented Design SEI, SJTU WEB APPS and SERVICES

The Object-Oriented... Hype l 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 l 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

OO Design vs. OO Programming l 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 l Object-Oriented Programming construction of software systems as Structured collection of Abstract Data Types (ADT) Inheritance Polymorphism concerned with programming languages and implementation issues

Polymorphism l Behavior promised in the public interface of superclass objects l implemented by subclass objects in the specific way required for the subclass l 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

Polymorphism Example

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

Causes of Rotting Design l 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) l Dependency Management the issue of coupling and cohesion It can be controlled! create dependency firewalls see DIP example

Open-Closed Principle (OCP) l "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

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

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

Strategic Closure "No significant program can be 100% closed " R.Martin, “The Open-Closed Principle,” 1996 Closure not complete but strategic lUse 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 lUse "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

OCP Heuristics l 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. l 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 Make all object-data private No Global Variables!

OCP Heuristics (2) l 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 l Not all these situations violate OCP all the time when used only as a "filter" RTTI is Ugly and Dangerous!

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

Inheritance Appears Simple class Bird { // has beak, wings,... public: virtual void fly(); // Bird can fly }; 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

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

Design by Contract l 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 require no 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

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

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 l The real problem void g(Rectangle& r) { r.setWidth(5); r.setHeight(4); // How large is the area? } 20!... Are you sure? ;-) l IS-A relationship must refer to the behavior of the class!

LSP is about Semantics and Replacement l The meaning and purpose of every method and class must be clearly documented Lack of user understanding will induce de facto violations of LSP l 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.

LSP and Replaceability l 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

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

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

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 R. Martin, 1996  OCP states the goal; DIP states the mechanism  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

Procedural vs. OO Architecture Procedural Architecture Object-Oriented Architecture

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

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

Design to an Interface l 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) l 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++

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

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

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

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

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