Principles of Object Oriented Design

Slides:



Advertisements
Similar presentations
Chapter 11 Component-Level Design
Advertisements

A practical guide John E. Boal TestDrivenDeveloper.com.
IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
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
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
Common mistakes Basic Design Principles David Rabinowitz.
Chapter 25 GRASP: More Objects with Responsibilities 1CS6359 Fall 2011 John Cole.
Common mistakes Basic Design Principles Amit Shabtay.
Developed by Reneta Barneva, SUNY Fredonia Component Level Design.
3/15/05H-1 © 2001 T. Horton CS 494 Object-Oriented Analysis & Design Evaluating Class Diagrams Topics include: Cohesion, Coupling Law of Demeter (handout)
Chapter 25 More Design Patterns.
CSc 335: Three More OO Design Principles
Chapter 7 Designing Classes. Class Design When we are developing a piece of software, we want to design the software We don’t want to just sit down and.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
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”.
CIT 590 Intro to Programming Style Classes. Remember to finish up findAllCISCourses.py.
1 OO Design Novosoft, 2001 by V. Mukhortov. 2 OO Design Goals  Flexibility Changes must be localized  Maintainability Modules requiring changes can.
CS 350 – Software Design The Object Paradigm – Chapter 1 If you were tasked to write code to access a description of shapes that were stored in a database.
Ch:10 Component Level Design Unit 4. What is Component? A component is a modular building block for computer software Because components reside within.
Company Confidential – Do Not Duplicate 2 Copyright 2008 McLane Advanced Technologies, LLC S.O.L.I.D. Software Development Achieving Object Oriented Principles,
© 2004 Capgemini - All rights reserved SOLID - OO DESIGN PRINCIPLES Andreas Enbohm, Capgemini.
Effective C#, Chapter 1: C# Language Elements Last Updated: Fall 2011.
CSE 301 Exam Revision Lecture
Introduction to SOLID Principles. Background Dependency Inversion Principle Single Responsibility Principle Open/Closed Principle Liskov Substitution.
S.O.L.I.D. Software Development 12 January 2010 (Martin Verboon, Patrick Kalkman, Stan Verdiesen)
Башкирцев (Старовер) Станислав JavaTalks OOD Principles.
SWE © Solomon Seifu ELABORATION. SWE © Solomon Seifu Lesson 12-5 Software Engineering Design Goals.
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
 What is SOLID  The S in SOLID  The O in SOLID  The L in SOLID  The I in SOLID  The D in SOLID  Questions.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
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.
Elements of OO Abstraction Encapsulation Modularity Hierarchy: Inheritance & Aggregation 4 major/essential elements3 minor/helpful elements Typing Concurrency.
REFACTORINGREFACTORING. Realities Code evolves substantially during development Requirements changes 1%-4% per month on a project Current methodologies.
OO Design Principles Copyright © Vyacheslav Mukhortov, Nikita Nyanchuk-Tatarskiy, Copyright © INTEKS LLC,
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Object-Oriented Principles Applications to Programming.
Design for testability as a way to good coding Simone Chiaretta Architect, Council of the EU December 9 th,
High Cohesion Low Coupling Old Standards for Object Oriented Programming.
Five design principles
CHAPTER 3 MODELING COMPONENT-LEVEL DESIGN.
PRINCIPLES OF OBJECT ORIENTED DESIGN S.O.L.I.D. S.O.L.I.D Principles What is SOLID?  Acrostic of 5 Principles:  The Single Responsibility Principle.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
SOLID Design Principles
These courseware materials are to be used in conjunction with Software Engineering: A Practitioner’s Approach, 6/e and are provided with permission by.
Session 33 More on SOLID Steve Chenoweth Office: Moench Room F220 Phone: (812) Chandan Rupakheti Office: Moench.
Duke CPS Programming Heuristics l Identify the aspects of your application that vary and separate them from what stays the same ä Take what varies.
SOLID PHP & Code Smell Wrap-Up
3/1/01H-1 © 2001 T. Horton CS 494 Object-Oriented Analysis & Design Evaluating Class Diagrams Topics include: Cohesion, Coupling Law of Demeter (handout)
Dependency Injection with Guice Technion – Institute of Technology Author: Gal Lalouche - Technion 2016 ©
Beginning Software Craftsmanship Brendan Enrick Steve Smith
14 Jul 2005CSE403, Summer'05, Lecture 09 Lecture 09: Fundamental Principles and Best Practices for Software Design Valentin Razmov.
Mantas Radzevičius ifm-2/2
Course information Old exam Resit Report Result and walkthrough
Software Architecture & Difference from Design
CMPE 135: Object-Oriented Analysis and Design October 24 Class Meeting
Copyright © by Curt Hill
Adaptive Code Umamaheswaran Senior Software Engineer
Object Oriented Practices
Component-Level Design
lecture 08, OO Design Principle
CMPE 135 Object-Oriented Analysis and Design March 21 Class Meeting
A (partial) blueprint for dealing with change
Principles of Object-Oriented Design
Object Oriented Design & Analysis
Interface Segregation Principle
Chapter 10 – Component-Level Design
Presentation transcript:

Principles of Object Oriented Design - John Teague & Mahendra Mavani

High Cohesion Low Coupling Old Standards for Object Oriented Programming

Problems Solved Maintainability Easier to Test Less Resistance to Change Fear to Change Code Leads to Old Stinky Code Reduces Repetition (DRY) Don’t Cut and Paste!!!! Allows For Continuous Improvement Essential for Agile Development

Topics To Discuss Single Responsibility Principle Dependency Inversion Principle Open Closed Principle Interface Segregation Principle Law of Demeter Liskov Substitution Principle

Single Responsibility Principle What is Responsibility? Reason for change Find how many reason you can think of for you class/method to change If more than one, then your design violates SRP

Single Responsibility Principle Requirement : Send monthly account statement to the customer <demo>

Single Responsibility Principle Problem:- we have more than one responsibility reading transaction record Formatting Sending Email Different user may want different email format IT Dept. may decide to change how data is stored Bank might want to start using third party email sending utility.

Single Responsibility Principle Refactor public class TransactionRepository {…. } public class HTMLMailFormater {….} public class EmailService {…….. } Demo

Dependency Inversion Depend upon abstraction High level module should not depend upon low level module implementation, rather depend upon abstraction Template pattern

Dependency Inversion Naïve Example Demo

Dependency Inversion Problem:- All the client must use text file to store transaction Sends email in HTML format only Code in BankAccount class, doesn’t depend upon storage but still can’t be tested in isolation.

Open Closed Principle Classes should be Open to Extensibility and Closed to Modifications To Change behavior, you want to add new code instead of modifying existing Code. May not have access to code

Why Keep Code Closed To Modifications Changing Existing Code is Risky. Can be Time Consuming in a Non-Refactored code base.

Code Not Designed on OCP private string SetDefaultEditableText() { StringBuilder editableText = new StringBuilder(); switch ( SurveyManager.CurrentSurvey.TypeID ) case 1: editableText.Append("<p>Text for Survey Type 2 Goes Here</p>"); case 2: case 3: default: editableText.Append("<p>Text for Survey Type 3 Goes Here</p>"); } return editableText.ToString();

Desigined For Extensibility Strategy Pattern (Composition focused) interface ISurveyEmailFormatter{ string GetDefaultEditableText(); } public SurveyType1EmailFormatter : ISurveyEmailFormatter{ public string GetDefaultEditableText(){ return "<p>Text for Survey Type 1 Goes Here</p>"; public SurveyType2EmailFormatter : ISurveyEmailFormatter{ public string GetDefaultEditableText(){ return "<p>Text for Survey Type 2 Goes Here</p>"; public SurveyType3EmailFormatter : ISurveyEmailFormatter{ return "<p>Text for Survey Type 3 Goes Here</p>";

Strategy Pattern Cont’d public class Survey{ IEmailFormatter _emailFormatter; public Survey(IEmailFormmater emailFormater){ _emailFormatter = emailFormatter; } public string GetEmailDefaultText(){ return _emailFormatter.GetDefaultEditableText();

Designed for Extensibility Template Pattern (Inheritance) public abstract Survey{ protected abstract string GetDefaultEditableText(); public string GetEmailText() { … string defaultText = GetDefaultEditableText(); return somthingHere; } public SurveyType1{ protected string GetDefaultEditableText() return "<p>Text for Survey Type 1 Goes Here</p>";

Extensibility Only Goes So far Change is going to occur and you can’t keep everything from changing Must use judgment on which parts of your application are more likely to change and focus extensibility there.

Law of Demeter Don’t Talk To Strangers Methods Should Only Talk To: Methods and fields on the Object Parameters passed into the method Objects Created within the method Only one “dot” foo.bar.baz (bad)

Demeter Breaking this principle breaks encapsulation, and tightens coupling. Refactoring much more difficult Test Setup becomes much more difficult

Demeter public class Wallet { double Cash{get;set;} } public class Customer Wallet Wallet{get;set;} public class Paperboy public double AmountCollected{get;set} public void CollectMoney(Customer customer, double amount){ if(customer.Wallet.Cash < amount) throw new InsufficientFundsException(); customer.Wallet.Cash -= amount; AmountCollected += customer.Wallet.Cash; The higher the degree of coupling between classes, the higher the odds that any change you make will break something somewhere else. This tends to create fragile, brittle code.

Demeter The fix: public class Wallet { double Cash{get;set;} public double Withdraw(double amount){ if(Cash < amount) throw new InsufficientFundsException(); Cash -= amount; return amount; } public class Customer Wallet Wallet{get;set;} public double Pay(double amount) Wallet.Withdraw(amount); public class Paperboy public double AmountCollected{get;set} public void CollectMoney(Customer customer, double amount) AmountCollected += customer.Pay(amount); http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf

Interface Segregation Princple Clients shouldn't be forced to implement interfaces they don't use

Interface Segregation Princple Example of FAT or Polluted Interface Try implementing custom Membership Provider in ASP.NET 2.0. You just need to implement 27 methods/properties

Interface Segregation Princple Interface Idoor { void Lock(); void UnLock(); bool IsOpen(); } Public Class Door : Idoor public void Lock() {} public void UnLock(){} bool IsOpen(){} <Demo>

Interface Segregation Princple Consider one implementation as security door which need to ring alarm if door is kept open for longer duration. Interface Idoor { void Lock(); void UnLock(); bool IsOpen(); void Timeout(); } public class SecurityDoor : Idoor void Lock() {} void UnLock() {} bool IsOpen() {} void Timeout() {} <Demo>

Interface Segregation Princple Problem All type of door are not timed By adding Timeout into IDoor we are polluting our interface

Interface Segregation Princple public interface ITimerClient { void TimeOut(); } public class SecurityDoor : IDoor, ITimerClient public void TimeOut() {…….}

Liskov Substitution Principle All sub-classes must be substitutable for their base class.

Liskov violation Structural Behavior You should not have to explicitly cast a base object to it’s subclass to do something. Behavior Subtypes should behave in a consistent manner in terms of their clients

Liskov Example public class LinkedList { public void copyInto(LinkedList dest) { dest.clear(); int n = getLength(); for(int i = 0; i < n; ++i){ dest.addElement(getElementAt(i)); } public class Set : LinkedList { ... /** * Adds element to this set, provided * element is not already in the set */ public void addElement(Object element) { if(!hasElement(element)) super.addElement(element); A later assignment asks the student to develop a set abstract data type. The student thinks, since a set is a list of non-duplicated elements, the set class could inherit from the linked list class saving lots of work and reusing code that already works. The only change would be to override the addElement method to provide the non-duplicated element requirement. Here is the student's set class:

Liskov Behavior of CopyInto will not always be consistent Set To Set is okay LinkedList to LinkedList is okay Set to LinkedList is okay LinkedList to Set behaves differently Linked List with {1, 2, 3, 2, 1} becomes {1, 2, 3} http://doodleproject.sourceforge.net/articles/2000/liskovSubstitutionPrinciple.html

Bottom line … SRP DIP OCP LSP LoD ISP Only one reason to change “Don’t call me, I’ll call you” OCP Open for extension, Closed for modification LSP Sub types should be substitutable for their bases types LoD “Don’t talk to strangers” ISP Clients should not be forced to depend on methods they do not use

Remember… Always code as if the guy maintaining your code would be a violent psychopath and he knows where you live.

References Uncle Bob’s blog http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod Los Techies Topic of the Month http://www.lostechies.com/blogs/chad_myers/archive/2008/03/07/pablo-s-topic-of-the-month-march-solid-principles.aspx