CSc 335: Three More OO Design Principles

Slides:



Advertisements
Similar presentations
General OO Concepts and Principles CSE301 University of Sunderland Harry R. Erwin, PhD.
Advertisements

Lecture 9 Improving Software Design CSC301-Winter 2011 – University of Toronto – Department of Computer Science Hesam C. Esfahani
Testing and Inheritance What is the relation between the test suite of a superclass and a subclass?
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
Classes and Object- Oriented... tMyn1 Classes and Object-Oriented Programming The essence of object-oriented programming is that you write programs in.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
Session 07: C# OOP 4 Review of: Inheritance and Polymorphism. Static and dynamic type of an object. Abstract Classes. Interfaces. FEN AK - IT:
Inheritance and object compatibility Object type compatibility An instance of a subclass can be used instead of an instance of the superclass, but not.
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,
Chapter 25 GRASP: More Objects with Responsibilities 1CS6359 Fall 2011 John Cole.
1 Topic 4 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“
Marcelo Santos – OOAD-CDT309, Spring 2008, IDE-MdH 1 Object-Oriented Analysis and Design - CDT309 Period 4, Spring 2008 Design Patterns: someone has already.
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.
Introduction to Object-oriented programming and software development Lecture 1.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
1 OO Design Novosoft, 2001 by V. Mukhortov. 2 OO Design Goals  Flexibility Changes must be localized  Maintainability Modules requiring changes can.
1 Abstraction  Identify important aspects and ignore the details  Permeates software development programming languages are abstractions built on hardware.
Company Confidential – Do Not Duplicate 2 Copyright 2008 McLane Advanced Technologies, LLC S.O.L.I.D. Software Development Achieving Object Oriented Principles,
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
More Design. Next Tuesday First draft of architectural design –use cases –class diagrams for major classes with responsibilities –sequence diagrams for.
© 2004 Capgemini - All rights reserved SOLID - OO DESIGN PRINCIPLES Andreas Enbohm, Capgemini.
CSE 301 Exam Revision Lecture
CSSE 374: More GRASP’ing for Object Responsibilities
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
1 Computer Science 340 Software Design & Testing Inheritance.
CPSC 372 John D. McGregor Module 4 Session 1 Design Patterns.
Law of Demeter. What is it: Style Rule for building systems. Proposed by my research group: The Demeter Research Group in 1987, published in Covered.
SWE © Solomon Seifu ELABORATION. SWE © Solomon Seifu Lesson 12-5 Software Engineering Design Goals.
Software Design Principles
1 Single Responsibility Principle Open Closed Principle Liskov Substitution Principle Law of Demeter CSC 335: Object-Oriented Programming and Design.
Incremental Design Why incremental design? Goal of incremental design Tools for incremental design  UML diagrams  Design principles  Design patterns.
OO Design Principles Copyright © Vyacheslav Mukhortov, Nikita Nyanchuk-Tatarskiy, Copyright © INTEKS LLC,
CPSC 871 John D. McGregor Module 5 Session 1 Design Patterns.
Salman Marvasti Sharif University of Technology Winter 2015.
High Cohesion Low Coupling Old Standards for Object Oriented Programming.
Five design principles
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Evaluating an Object-Oriented Design ©SoftMoore ConsultingSlide 1.
1. Perspectives on Design Principles – Semantic Invariants and Design Entropy Catalin Tudor 2.
Inheritance Type/Subtype Relationship. Inheritance Idea: An object B of one type, termed child class, inherits from another object A of another type,
Principles of Object Oriented Design
SOLID Design Principles
Class Inheritance SWE 344 Internet Protocols & Client Server Programming.
Chapter 7 Classes and Methods III: Static Methods and Variables Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition)
Class Relationships Lecture Oo08 Polymorphism. References n Booch, et al, The Unified Modeling Language User Guide, Chapt 10 p.125 n Fowler & Scott, UML.
The Law of Demeter For Operating System Course. Motivation Several programs were written in bad style Are difficult to maintain There is a simple remedy.
Testing in OO Environment The reasons for testing is not any different for any of the design and implementation methodologies, including OO methodology.
3/1/01H-1 © 2001 T. Horton CS 494 Object-Oriented Analysis & Design Evaluating Class Diagrams Topics include: Cohesion, Coupling Law of Demeter (handout)
Beginning Software Craftsmanship Brendan Enrick Steve Smith
1 The Law of Demeter By Rick Mercer with help from Object-Oriented Design Heuristics, Arthur Riel Addison-Wesley, 1996, ISBN X and Applying.
CSCI 383 Object-Oriented Programming & Design Lecture 15 Martin van Bommel.
Course information Old exam Resit Report Result and walkthrough
Copyright © Jim Fawcett Spring 2017
Object-Oriented Programming Concepts
Software Design Principles
Inheritance ITI1121 Nour El Kadri.
Low Budget Productions, LLC
Copyright © by Curt Hill
EECE 310: Software Engineering
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Software Design Principles
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Subtype Polymorphism, Subtyping vs
Software Design Lecture : 12.
Software Design Lecture : 14.
Principles of Object-Oriented Design
Object Oriented Design & Analysis
Law of Demeter (LoD) 7/23/2019 LoD
Presentation transcript:

CSc 335: Three More OO Design Principles Open Closed Principle Law of Demeter Liskov Substitution Principle

Four Design Smells Rigidity-One change requires many other changes Fragility-One change breaks other parts Immobility-Can't pull out a piece to reuse Needless Repetition-Repeated code is evil, to change the logic, change must happen in many places

Open Closed Principle "All systems change during their life-cycles. This must be born in mind when developing systems expected to last longer than the first version", Ivar Jacobsen Software entities (classes modules, functions, etc) should be open for extension but closed for modification, Bertrand Meyer 1988 Now known as the Open-Closed Principle

Modules that never change? If a change to one module (class or method) results in a cascade of changes to other modules, you have bad design When requirements change (and they always do), your design should allow developers to extend the behavior by adding new code good design rather than changing the behavior of existing code bad design

Open and Closed? The behavior of a module should be extended--as in adding behavior An analogy: can add extensions to a house leaving other rooms intact at least relatively Use an abstract classes and extends or interfaces and implements The source code of this kind of module can not be changed

One Design Imagine Client represents any module that depends on some other module named Server

Abstraction Client depends on an abstraction that does not change. It could be an abstract class or an interface

Example: Strategy Pattern Previous UML showed the general form Next slide shows has UML diagram of a specific application of the Strategy pattern It is also an application of the open closed principle Which class plays the role of client? Which class plays the role of AbstractServer? Why is Strategy OPEN/CLOSED?

Example: Strategy Pattern

Another Example Strategy follows the Open-Closed Principle because implementing a new Strategy does not require a change to the Player Class This class is essentially closed for modification  Because we can pass in an object that implements ComputerStrategy, the class is open for extension Extending Player (the client) only requires new modules (classes) be written that implement ComputerStrategy There are no changes to the existing Player

Other Examples Eclipse Using List parameters and return types Plugins can be added to with no changes to Eclipse Plugins "extends" Eclipse Using List parameters and return types A module depends on List rather than a concrete class like ArrayList, LinkedList, or Vector If you change ArrayList, or develop a new List class, you don't change clients that depends on it

Comparator is Open Closed public class ComparatorTest { @Test public void testComparators() { BankAccount a = new BankAccount("A", 5); BankAccount b = new BankAccount("B", 100); BankAccount c = new BankAccount("C", 3000); BankAccount d = new BankAccount("D", 200); BankAccount e = new BankAccount("E", 50); List<BankAccount> accounts = new ArrayList<BankAccount>(); // Add "randomly" so these are not sorted. accounts.add(e); accounts.add(c); accounts.add(d); accounts.add(a); accounts.add(b);

Comparator is Open Closed Comparator<BankAccount> idComparator = new ByID(); Collections.sort(accounts, idComparator); System.out.println(accounts); // First element has the alphabetically first ID assertEquals("A", accounts.get(0).getID()); Comparator<BankAccount> balanceComparator = new ByBalance(); Collections.sort(accounts, balanceComparator); // First element has the most money assertEquals("C", accounts.get(0).getID()); }

The Two Comparators import java.util.Comparator; public class ByID implements Comparator { public int compare(Object arg0, Object arg1) { BankAccount left = (BankAccount) arg0; BankAccount right = (BankAccount) arg1; return left.getID().compareTo(right.getID()); } public class ByBalance implements Comparator { return (int) ((100 * right.getBalance()) - 100 * left.getBalance());

Law of Demeter A style rule for designing object-oriented systems "Only talk to your immediate friends" Name of the Greek Goddess of Agriculture In other words, grow software in small steps Each module should have only limited knowledge about other modules Those "closely" related to the current unit Each module only talks to friends “Don't talk to strangers”

Law of Demeter This is low coupling in software engineering made more explicit Try to avoid knowing about the structure of indirect objects Use the direct object that you need to know about and let that object talk to indirect objects

Who are closely related friends? From a method, messages can be sent to this object a parameter of the method an instance variable of this object an object created within the method

FRIENDS

An Example Widely used in big projects, for example, at the Jet Propulsion Laboratory (JPL) for the Mars exploration software, the quote The Law of Demeter … has taken a firm hold in many areas of JPL. Major systems which have used LoD extensively include … Mars Pathfinder Software. We are going to use LoD as a foundational software engineering principle for the X2000 Europa orbiter mission.

Grady Booch says The basic effect of applying this Law is the creation of loosely coupled classes Encapsulate implementation secrets Such classes are fairly unencumbered To understand the meaning of one class, you need not understand the details of many other classes

Abstract example class A { private B b = new B(); public void m() { this.b.c.foo(); // High coupling: bad } class B { C c; class C { public void foo() {

Silly example you already coded? Which code represents the better design? // a. dog.body.tail.wag(); // b. dog.expressHappiness(); The bad example couples dog to two indirect classes DogBody, and DogTail The good design couples dog only to the direct class DogAnimal

Liskov Substitution Principle The Liskov Substitution Principle of object oriented design states In class hierarchies, it should be possible to treat a specialized object as if it were a base class object Code with a reference to a base class should be able to use objects of the derived class without knowing it

From the source in 1988 Barbara Liskov first wrote this: “What is wanted is something like the following substitution property: If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2, then S is a subtype of T.“ Or more simply: Subtypes must be substitutable for their base types"

Consider this code public class Rectangle { protected int _width; protected int _height; public int getWidth() { return _width; } public int getHeight() { return _height; public void setWidth(int width) { _width = width; public void setHeight(int height) { _height = height;

Let Square be a subtype of Rectangle class Square extends Rectangle { @Override public void setWidth(int width) { _width = width; _height = width; } public void setHeight(int height) { _height = height; _width = _height;

Compiles, but does it pass? import static org.junit.Assert.*; import org.junit.Test; public class RectangleTest { @Test public void testArea() { Rectangle r = new Square(); r.setWidth(5); r.setHeight(2); // Does this assertion pass? assertEquals(10, r.getWidth() * r.getHeight()); }

Solution? If the behavior by Square is unacceptable and unexpected, Square should not be derived from Rectangle

Why follow Liskov? Liskov basically wants you to think clearly about the expected behavior and expectations of a class before you derive new classes from it  It could turn out that when subtypes are substituted for a parent, you may get unexpected results  Unit tests help avoid this problem