+ All Categories
Home > Documents > Principles of Object Oriented Design

Principles of Object Oriented Design

Date post: 24-Feb-2016
Category:
Upload: archie
View: 55 times
Download: 0 times
Share this document with a friend
Description:
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 - PowerPoint PPT Presentation
35
Principles of Object Oriented Design - John Teague & Mahendra Mavani
Transcript

Principles of Object Oriented Design

Principles of Object Oriented Design- John Teague & Mahendra MavaniHigh Cohesion

Low CouplingOld Standards for Object Oriented Programming

Problems SolvedMaintainabilityEasier to TestLess Resistance to ChangeFear to Change Code Leads to Old Stinky CodeReduces Repetition (DRY)Dont Cut and Paste!!!!Allows For Continuous ImprovementEssential for Agile Development

Topics To DiscussSingle Responsibility PrincipleDependency Inversion PrincipleOpen Closed PrincipleInterface Segregation PrincipleLaw of DemeterLiskov Substitution Principle4Single Responsibility PrincipleWhat is Responsibility?Reason for changeFind how many reason you can think of for you class/method to changeIf more than one, then your design violates SRPSingle Responsibility PrincipleRequirement :Send monthly account statement to the customer

Single Responsibility PrincipleProblem:-we have more than one responsibility reading transaction recordFormattingSending EmailDifferent user may want different email formatIT Dept. may decide to change how data is storedBank might want to start using third party email sending utility.Single Responsibility PrincipleRefactorpublic class TransactionRepository {. }public class HTMLMailFormater {.}public class EmailService {.. }

DemoDependency InversionDepend upon abstractionHigh level module should not depend upon low level module implementation, rather depend upon abstractionTemplate patternDependency InversionNave Example DemoDependency InversionProblem:-All the client must use text file to store transactionSends email in HTML format onlyCode in BankAccount class, doesnt depend upon storage but still cant be tested in isolation.

Open Closed PrincipleClasses should be Open to Extensibility and Closed to ModificationsTo Change behavior, you want to add new code instead of modifying existing Code.May not have access to codeWhy Keep Code Closed To ModificationsChanging Existing Code is Risky.Can be Time Consuming in a Non-Refactored code base.Code Not Designed on OCPprivate string SetDefaultEditableText(){StringBuilder editableText = new StringBuilder();

switch ( SurveyManager.CurrentSurvey.TypeID ){case 1:editableText.Append("Text for Survey Type 2 Goes Here");case 2:editableText.Append("Text for Survey Type 2 Goes Here");case 3:default:editableText.Append("Text for Survey Type 3 Goes Here");}return editableText.ToString();}Desigined For ExtensibilityStrategy Pattern (Composition focused)interface ISurveyEmailFormatter{string GetDefaultEditableText();}public SurveyType1EmailFormatter : ISurveyEmailFormatter{public string GetDefaultEditableText(){return "Text for Survey Type 1 Goes Here";}}

public SurveyType2EmailFormatter : ISurveyEmailFormatter{public string GetDefaultEditableText(){return "Text for Survey Type 2 Goes Here";}}

public SurveyType3EmailFormatter : ISurveyEmailFormatter{public string GetDefaultEditableText(){return "Text for Survey Type 3 Goes Here";}}

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

}Designed for ExtensibilityTemplate Pattern (Inheritance)public abstract Survey{protected abstract string GetDefaultEditableText();public string GetEmailText(){ string defaultText = GetDefaultEditableText();return somthingHere;}

}

public SurveyType1{protected string GetDefaultEditableText(){ return "Text for Survey Type 1 Goes Here";}}Extensibility Only Goes So farChange is going to occur and you cant keep everything from changingMust use judgment on which parts of your application are more likely to change and focus extensibility there.

Law of DemeterDont Talk To StrangersMethods Should Only Talk To:Methods and fields on the ObjectParameters passed into the methodObjects Created within the methodOnly one dotfoo.bar.baz (bad)DemeterBreaking this principle breaks encapsulation, and tightens coupling.Refactoring much more difficult Test Setup becomes much more difficult

Demeterpublic 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.

21DemeterThe 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.pdfInterface Segregation PrincpleClients shouldn't be forced to implement interfaces they don't useInterface Segregation PrincpleExample 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 PrincpleInterface Idoor{void Lock();void UnLock();bool IsOpen();}Public Class Door : Idoor{public void Lock() {}public void UnLock(){}bool IsOpen(){}}

Interface Segregation PrincpleConsider 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() {}}

Interface Segregation PrincpleProblemAll type of door are not timed By adding Timeout into IDoor we are polluting our interfaceInterface Segregation Princplepublic interface ITimerClient { void TimeOut(); }public class SecurityDoor : IDoor, ITimerClient {public void TimeOut(){.} }Liskov Substitution PrincipleAll sub-classes must be substitutable for their base class.Liskov violationStructuralYou should not have to explicitly cast a base object to its subclass to do something.BehaviorSubtypes should behave in a consistent manner in terms of their clientsLiskov Examplepublic 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:31LiskovBehavior of CopyInto will not always be consistentSet To Set is okayLinkedList to LinkedList is okaySet to LinkedList is okayLinkedList to Set behaves differentlyLinked List with {1, 2, 3, 2, 1} becomes {1, 2, 3}

http://doodleproject.sourceforge.net/articles/2000/liskovSubstitutionPrinciple.htmlBottom line SRP Only one reason to changeDIP Dont call me, Ill call youOCP Open for extension, Closed for modificationLSP Sub types should be substitutable for their bases typesLoD Dont talk to strangersISP Clients should not be forced to depend on methods they do not use33Remember Always code as if the guy maintaining your code would be a violent psychopath and he knows where you live.References

Uncle Bobs bloghttp://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOodLos Techies Topic of the Monthhttp://www.lostechies.com/blogs/chad_myers/archive/2008/03/07/pablo-s-topic-of-the-month-march-solid-principles.aspx


Recommended