Open Closed Principle (OCP)

Similar documents
Single Responsibility Principle (SRP)

Liskov Substitution Principle

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

Software Engineering Design & Construction Dr. Michael Eichberg Fachgebiet Softwaretechnik Technische Universität Darmstadt

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

Software Engineering

Principles of Object-Oriented Design

OO Class Design Principles

Produced by. Agile Software Development. Eamonn de Leastar

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

SOLID: Principles of OOD

Outline. Software Rots

Bruno Bossola SOLID Design Principles

CSC207H: Software Design SOLID. CSC207 Winter 2018

Conception Orientée Objets. Programmation SOLID

17.11 Bean Rules persistent

Software Engineering Design & Construction

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

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

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

Why Use Object-Oriented Programming in the First Place?

Object Oriented Software Design - I

CS 520 Theory and Practice of Software Engineering Fall 2017

Intro to: Design Principles

CS 320 Introduction to Software Engineering Spring March 06, 2017

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

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

CS 520 Theory and Practice of Software Engineering Fall 2018

Principles of OO Design

CHAPTER 5: PRINCIPLES OF DETAILED DESIGN

Inheritance and object compatibility

Software Design and SOLID Principles

Component-Level Design. Slides copyright 1996, 2001, 2005, 2009 by Roger S. Pressman. For non-profit educational use only

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

Object-Oriented Design I - SOLID

Lecture: Modular Design

Component-Level Design

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

09. Component-Level Design

Highlights of Previous Lecture

Design Principles: Part 2

Java Object Oriented Design. CSC207 Fall 2014

Design Principles: Part 2

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

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

Class Design Principles

Chapter 5 Object-Oriented Programming

Recap of OO concepts. Objects, classes, methods and more. Mairead Meagher Dr. Siobhán Drohan. Produced by:

[ L5P1] Object-Oriented Programming: Advanced Concepts

20 Years of. Improve the Design of your Code. Dr Dimitris Dranidis JAVA Meetup Group, Thessaloniki May 2015

Influence of Design Patterns Application on Quality of IT Solutions

COURSE 2 DESIGN PATTERNS

1: Introduction to Object (1)

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

Basic design patterns

CS1004: Intro to CS in Java, Spring 2005

Lessons Learned. Johnny Bigert, Ph.D., Skype/Microsoft October 26, 2011

OO Design Principles

Software Engineering I (02161)

Object-Oriented Concepts and Design Principles

Object-Oriented Design

Bridge Pattern. Used to decouple an abstraction from its implementation so that the two can vary independently

Dependency Inversion, Dependency Injection and Inversion of Control. Dependency Inversion Principle by Robert Martin of Agile Fame

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

The Object Oriented Paradigm

CS 320 Introduction to Software Engineering Spring March

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Principles of Ruby Applica3on Design. Dean Wampler Senior Mentor and Consultant Object Mentor, Inc. Chicago, IL

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

Single Responsibility Principle

Object-oriented design principles

The S.O.L.I.D. Principles. of Object Oriented Programming

Learning Objectives. C++ For Artists 2003 Rick Miller All Rights Reserved xli

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

SOFTWARE PATTERNS. Joseph Bonello

The following topics will be covered in this course (not necessarily in this order).

Summary of the course lectures

Introduction to Object-Oriented Programming

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

Object-Oriented Design

Introduction to Testing and Maintainable code

Dependency Injection & Design Principles Recap Reid Holmes

Build Testable Client and Service Applications

CSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich

Understading Refactorings

Object-Oriented Software Engineering. Chapter 2: Review of Object Orientation

OOD Smells and Principles

OBJECT ORIENTED SYSTEM DEVELOPMENT Software Development Dynamic System Development Information system solution Steps in System Development Analysis

CSC207 Week 3. Larry Zhang

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

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

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING

DevOps and Maven. Eamonn de Leastar Dr. Siobhán Drohan Produced by:

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Introduction to Object Oriented Programming. (Hebrew University, CS / Spring 2012 )

Self-review Questions

Tecniche di Progettazione: Design Patterns

Object-Oriented Software Engineering Practical Software Development using UML and Java. Chapter 2: Review of Object Orientation

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding

Transcription:

Open Closed Principle (OCP) Produced by: Eamonn de Leastar (edeleastar@wit.ie) Dr. Siobhán Drohan (sdrohan@wit.ie) Department of Computing and Mathematics http://www.wit.ie/

SOLID Class Design Principles In the mid-1990s, Robert C. Martin gathered five principles for object-oriented class design, presenting them as the best guidelines for building a maintainable object oriented system. Michael Feathers attached the acronym SOLID to these principles in the early 2000s.

SOLID Class Design Principles S O L I D Single Responsibility Principle (SRP). Classes should have one, and only one, reason to change. Keep your classes small and single-purposed. Open-Closed Principle (OCP). Design classes to be open for extension but closed for modification; you should be able to extend a class without modifying it. Minimize the need to make changes to existing classes. Liskov Substitution Principle (LSP). Subtypes should be substitutable for their base types. From a client s perspective, override methods shouldn t break functionality. Interface Segregation Principle (ISP). Clients should not be forced to depend on methods they don t use. Split a larger interface into a number of smaller interfaces. Dependency Inversion Principle (DIP). High-level modules should not depend on low-level modules; both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions.

SOLID Class Design Principles Module Scope S O L I D Single Responsibility Principle (SRP). Classes should have one, and only one, reason to change. Keep your classes small and single-purposed. Open-Closed Principle (OCP). Design classes to be open for extension but closed for modification; you should be able to extend a class without modifying it. Minimize the need to make changes to existing classes. Liskov Substitution Principle (LSP). Subtypes should be substitutable for their base types. From a client s perspective, override methods shouldn t break functionality. Interface Segregation Principle (ISP). Clients should not be forced to depend on methods they don t use. Split a larger interface into a number of smaller interfaces. Dependency Inversion Principle (DIP). High-level modules should not depend on low-level modules; both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions.

Change happens! All systems change during their lifecycles. This must be borne in mind when developing systems expected to last longer than the first version. (Jacobson et al., 1992)

O in SOLID - Open-Closed Principle The Open/Closed Principle Software entities (classes, modules, methods, etc.) should be open for extension but closed for modification. The idea is that it s often better to make changes to things like classes by adding to or building on top of them (using mechanisms like subclassing or polymorphism) rather than modifying their code.

OCP - avoidance of rigid code When a single change to a program results in a cascade of changes to dependent modules: design smells of rigidity. OCP advice: refactor the system so further changes of that kind will not cause more modifications. OCP ideal: further changes of that kind are achieved by adding new code, NOT by changing code that already exists.

Open and Closed? Contradiction? 9

Open and Closed? Contradiction? Open For Extension: the behavior of the module can be extended. the module can be made to behave in new and different ways as the requirements of the application change. Closed for Modification: extending the behaviour of the module does not result in changes to the source (or binary) code of the module. 10

Open and Closed? Contradiction? The normal way to extend the behavior of a module is to make changes to the source code of that module. A module that cannot be changed is normally thought to have a fixed behavior. How can these two opposing attributes be resolved? 11

Abstraction Create abstractions that: are fixed. will be the abstract base classes. represent an unbounded group of possible behaviours (i.e. all the possible derived classes). It is possible for a module to manipulate an abstraction. The abstraction is: Closed for modification it is fixed. Open for extension can create new derivative classes of the abstraction.

Open-Closed Principle So, the idea is that it s often better to make changes to things like classes by adding to or building on top of them (using mechanisms like sub-classing or polymorphism) rather than modifying their code.

Open-Closed Principle OCP states: Design modules that never change. When requirements change: you extend the behavior of such modules by adding new code. not by changing old code that already works. 14

Source Material - OCP first characterized in OOSC... The book, known among its fans as "OOSC", presents object technology as an answer to major issues of software engineering, with a special emphasis on addressing the software quality factors of correctness, robustness, extendibility and reusability. It starts with an examination of the issues of software quality, then introduces abstract data types as the theoretical basis for object technology and proceeds with the main object-oriented techniques: classes, objects, genericity, inheritance, Design by Contract,concurrency, and persistence. It includes extensive discussions of methodological issues. http://en.wikipedia.org/wiki/object-oriented_software_construction http://en.wikipedia.org/wiki/open/closed_principle 16

An Abstract Example of OCP

Example (1) Module A is used by client modules B, C, D, which may themselves have their own clients (E). 18

Example (2) A new client Bx requires an extended or adapted version of A called Ax. Further clients of Ax are developed (F, G, I) 19

Example (3) With non-oo methods, there are two solutions: 1. Adapt module A so that it will offer the extended or modified functionality required by the new clients. 2. Leave A as it is, make a copy, change the module s name to Ax, and perform all the necessary adaptations on the new module. With this technique Ax retains no further connection to A. 20

Solution-1 (modify A s functionality) A may have been around for a long time and have many clients such as B, C and D. The adaptations needed to satisfy the new clients requirements may invalidate the assumptions on the basis of which the old ones used A. Change to A may start a dramatic series of changes in clients, clients of clients and so on. Nightmare scenario: Entire parts of the software that were supposed to have been finished and sealed are reopened, triggering a new cycle of development, testing, debugging and documentation. 21

Solution-2 (copy A, paste as Ax) On the surface, solution 2 seems better as it does not require modifying any existing software. But this solution may be even more catastrophic since it only postpones the day of reckoning. Leads to an explosion of variants of the original modules, many of them very similar to each other although never quite identical. 22

Solution-2 Abundance of modules, not matched by abundance of available functionality (many of the apparent variants being in fact quasi-clones), creates a huge configuration management problem. 23

OO Solution Abstraction, Interfaces & Inheritance Using interfaces and inheritance developers can adopt a much more incremental approach. 24

Returning to Abstraction In Java it is possible to create abstractions that are fixed and yet represent an unbounded group of possible behaviors: Specified as interfaces and abstract classes. The unbounded group of possible behaviors is represented as derived classes and classes that implement the interfaces. A module can implement these abstractions: Can be closed for modification since it fulfills an abstraction that is fixed. Yet the behavior of that module can be extended by creating new implementations of the abstraction. 25

Client and Server Example

Client is not open and closed Client Server Both Client and Server are concrete Java classes and Client uses Server. If we want the Client to use a different server, the Client source code must be modified to use the new server class: Client is directly coupled to Server. Violation of OCP: extending the behaviour of Client results in modifications to its source code. 27

Client is both open and closed Client <<interface>> ClientInterface ClientInterface is abstract with abstract member functions: i.e. closed for modification. Server implements ClientInterface. Server Client uses ClientInterface: However, objects of the Client class will be using objects of the derivative Server class. If we want Client to use a different server class, a new derivative of the ClientInterface can be created. The Client class can remain unchanged. i.e. open for extension. 28

Shape Example

Shape Example Application must be able to draw circles and squares on a standard GUI. The circles and squares must be drawn in a particular order. A list of the circles and squares will be created in the appropriate order and the program must walk the list in that order and draw each circle or square. 30

Shape Example 1 (violates OCP) Shape uses <<enum>> ShapeType Circle Square uses Point uses uses Server uses

Shape Example 1 (violates OCP) public class Point { private double xcoord; private double ycoord; public Point(){ this.setxcoord(0.0); this.setycoord(0.0); public Point(double xcoord, double ycoord){ this.setxcoord(xcoord); this.setycoord(ycoord); public class Shape { private ShapeType type; // getter and setter public enum ShapeType { CIRCLE, SQUARE // getter and setter methods

Shape Example 1 (violates OCP) public class Circle extends Shape { private double radius; private Point center; public Circle() { super.settype(shapetype.circle); this.setradius(10); //default size this.setcenter(new Point()); //default location // getter methods // setter methods

Shape Example 1 (violates OCP) public class Square extends Shape { private double length; private Point leftcorner; public Square() { super.settype(shapetype.square); this.setlength(10); //default size this.setleftcorner(new Point()); //default location // getter methods // setter methods

Shape Example 1 (violates OCP) public class Server { void drawsquare(square square) { System.out.println("I'm drawing a square"); void drawcircle(circle circle) { System.out.println("I'm drawing a circle"); void drawallshapes(list<shape> shapes) { for (Shape shape : shapes) { switch (shape.gettype()) { case SQUARE: drawsquare((square) shape); break; case CIRCLE: drawcircle((circle) shape); break; public static void main(string args[]){ List<Shape> shapes = new ArrayList<>(); shapes.add(new Circle()); shapes.add(new Square()); shapes.add(new Circle()); Server app = new Server(); app.drawallshapes(shapes);

Proposed Extension : Triangle public class Triangle extends Shape { private Point pointa; private Point pointb; private Point pointc; public Triangle() { super.settype(shapetype.triangle); this.setpointa(new Point()); this.setpointb(new Point()); this.setpointc(new Point()); // getter methods // setter methods public enum ShapeType { CIRCLE, SQUARE, TRIANGLE Open for Extension? Yes. New Triangle class. 36

Proposed Extension : Triangle public class Server { void drawsquare(square square) { System.out.println("I'm drawing a square"); void drawcircle(circle circle) { System.out.println("I'm drawing a circle"); void drawallshapes(list<shape> shapes) { for (Shape shape : shapes) { switch (shape.gettype()) { case SQUARE: drawsquare((square) shape); break; case CIRCLE: drawcircle((circle) shape); break; Open or Closed for Modification? 37

Proposed Extension : Triangle void drawsquare(square square) { System.out.println("I'm drawing a square"); void drawcircle(circle circle) { System.out.println("I'm drawing a circle"); void drawtriangle(triangle triangle) { System.out.println("I'm drawing a triangle"); Class has to be modified to include new shape type Not Closed for Modification! Server class void drawallshapes(list<shape> shapes) { for (Shape shape : shapes) { switch (shape.gettype()) { case SQUARE: drawsquare((square) shape); break; case CIRCLE: drawcircle((circle) shape); break; case TRIANGLE: drawtriangle((triangle) shape); break; 38

Shape Example 2 (conforming to OCP) <<interface>> Shape Circle Square uses Point uses uses Server uses

Shape Example 2 (conforming to OCP) public class Circle implements Shape { private double radius; private Point center; public Circle() { this.setradius(10); //default size this.setcenter(new Point()); //default location public void draw() { System.out.println("I'm drawing a circle"); //getters and setters public interface Shape { public void draw(); Interface defines abstraction Shape. Circle implements this abstraction.

Shape Example 2 (conforming to OCP) public class Square implements Shape { private double length; private Point leftcorner; public Square() { this.setlength(10); //default size this.setleftcorner(new Point()); //default location public void draw() { System.out.println("I'm drawing a square"); //getters and setters public interface Shape { public void draw(); Interface defines abstraction Shape. Square implements this abstraction.

Shape Example 2 (conforming to OCP) public class Server { void drawallshapes(list<shape> shapes) { for (Shape shape : shapes) { shape.draw(); //rest of code drawallshapes method is changed to refer to Shape only.

Open and Closed Is Shape interface open to extension (e.g. Triangle)? Yes! Is Server closed for this extensions? Yes! public class Triangle implements Shape { private Point pointa; private Point pointb; private Point pointc; public void draw() { System.out.println("I'm drawing a triangle"); public class Server { void drawallshapes(list<shape> shapes) { for (Shape shape : shapes) { shape.draw(); //rest of code Server s behaviour can be extended without modification it is closed. 43

Strategic Closure (1) It should be clear that no significant program can be 100% closed. Consider what would happen to the drawallshapes methods (on the previous slide) if: we decided that all Circles should be drawn before any Squares. The drawallshapes method is NOT closed against a change like this. In general, no matter how closed a module is, there will always be some kind of change against which it is not closed.

Strategic Closure (2) Since closure cannot be complete, it must be strategic. That is, the designer must choose the kinds of changes against which to close his/her design. This takes a certain amount of foresight derived from experience. The experienced designer knows the users and the industry well enough to judge the probability of different kinds of changes. S/he then makes sure that the open-closed principle is invoked for the most probable changes.

Without OCP: OCP Summary code tends to have large switch statements or if-then constructions, possibly enums. adding a new implementation (type) means adding new code to the client of the type. the client of a class must be aware of all subclasses. With OCP: Use abstraction and dynamic binding to avoid dependency on a concrete class. The abstraction is: Closed for modification it is fixed. Open for extension can create new derivative classes of the abstraction. 46

References Jacobson, I., Johnsson, P., Christerson, M. & Overgaard, G. (1992) Object-Oriented Software Engineering: A Use Case Driven Approach, Addison- Wesley.

Except where otherwise noted, this content is licensed under a Creative Commons Attribution- NonCommercial 3.0 License. For more information, please see http://creativecommons.org/licenses/by-nc/3.0/