lecture 13 law of demeter. cohesion cohesion: the “glue” that holds a module together. don’t...

25
Lecture 13 Lecture 13 Law of Demeter Law of Demeter

Upload: moris-bridges

Post on 29-Jan-2016

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

Lecture 13Lecture 13

Law of DemeterLaw of Demeter

Page 2: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

CohesionCohesion

• CohesionCohesion: the “glue” that holds a module : the “glue” that holds a module together. Don’t do things that do not support together. Don’t do things that do not support a common goala common goal

• As with coupling there are degrees of As with coupling there are degrees of cohesioncohesion

• Listed from most to least desirableListed from most to least desirable

Page 3: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

Taxonomy of CohesionTaxonomy of Cohesion

• Data CohesionData Cohesion: A module implements a : A module implements a data abstractiondata abstraction

• Functional CohesionFunctional Cohesion: All elements are : All elements are dedicated to performing a single functiondedicated to performing a single function

• Sequential CohesionSequential Cohesion: Calling the elements : Calling the elements in a specific orderin a specific order

• Communication CohesionCommunication Cohesion: All elements : All elements operate on the same input/output dataoperate on the same input/output data

Page 4: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

Taxonomy of Cohesion (ctd)Taxonomy of Cohesion (ctd)

• Temporal CohesionTemporal Cohesion: Elements are invoked : Elements are invoked at or near the same timeat or near the same time

• Logical CohesionLogical Cohesion: If tasks the elements : If tasks the elements perform are conceptually relatedperform are conceptually related

• Coincidental CohesionCoincidental Cohesion: If the tasks the : If the tasks the elements perform are totally unrelatedelements perform are totally unrelated

Page 5: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

Functional CohesionFunctional Cohesion

• Elements perform tasks in a specific domain Elements perform tasks in a specific domain for a specific purposefor a specific purpose

• Meyers: “The purpose of an informational Meyers: “The purpose of an informational strength module is to hide some concept, strength module is to hide some concept, data structure or resource in a single data structure or resource in a single module”module”

class bakeCake{ void addIngredients(){...} void mixBatter(){...} void bake(){...}}

Page 6: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

Sequential CohesionSequential Cohesion

• The output from one element becomes the The output from one element becomes the input for anotherinput for another

• The previous example is sequentially The previous example is sequentially cohesive, because the order and tasks cohesive, because the order and tasks performed are sequentially determinedperformed are sequentially determined

• Bad for reusability and maintainabilityBad for reusability and maintainability

Page 7: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

Communication CohesionCommunication Cohesion

• Share portions of a common data structure Share portions of a common data structure or parametersor parameters

• Example:Calculate employee statistics and Example:Calculate employee statistics and write monthly paycheckwrite monthly paycheck

• ProblemsProblems Wide interfaceWide interface Bad reusability and maintenenaceBad reusability and maintenenace

• Cure: Isolate each sharing member into a Cure: Isolate each sharing member into a separate moduleseparate module

Page 8: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

Temporal CohesionTemporal Cohesion

• Tasks are performed at about the same timeTasks are performed at about the same time• E.g. Initialize a program at boot timeE.g. Initialize a program at boot time• Main problem: Multiple functions, elements Main problem: Multiple functions, elements

are not necessarily cohesiveare not necessarily cohesive

class initStuff{ void initMemory(){...} void initDisk(){...} void initPrinter{...}}

Page 9: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

Logical CohesionLogical Cohesion

• Tasks are conceptually related, but no data Tasks are conceptually related, but no data or control connectionor control connection

• Problems:Problems: Wide InterfaceWide Interface Multiple FunctionsMultiple Functions

class areaUtils{ double squareArea(){...} double triangArea(){...} double circleArea(){...}}

Page 10: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

Coincidental CohesionCoincidental Cohesion

• The worst kind: the “kitchen sink”. No real The worst kind: the “kitchen sink”. No real reason for groupingreason for grouping

• Big offender one-class JavaBig offender one-class Java• Problems:Problems:

Multiple functionalityMultiple functionality Result of poor maintenanceResult of poor maintenance

class myStuff{ void initPrinter(){...} double calculateTaxes(){...} Date getDate(){...}

Page 11: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

Also: Procedural CohesionAlso: Procedural Cohesion

• Associate elements on the basis of Associate elements on the basis of algorithmic or procedural relationshipsalgorithmic or procedural relationships

• First do A then B, hence put them together First do A then B, hence put them together in one method or elementin one method or element

class Stack{... public void push(){int addMe=readInt (“Type an int”); elements{++sp]=addMe;} public void pop(){int next=elements[SP--]; println(next);}}

Page 12: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

Law of Demeter (LoD)Law of Demeter (LoD)

• Good technique for reducing coupling Good technique for reducing coupling between objects in programming codebetween objects in programming code

• Proven “Industrial Strength”. i.e. used in Proven “Industrial Strength”. i.e. used in major SW projects to reduce maintenance major SW projects to reduce maintenance costscosts

• Let’s look at an exampleLet’s look at an example

Page 13: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

POST ProjectPOST Project

• Consider a customer at check-out:Consider a customer at check-out:

public class Customer{ private String firstName; private String lastName; private String myWallet; public String getFirstName(){return firstName;} public String getLastName(){return lastName;} public String getWallet(){ return myWallet:]

Page 14: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

POST ProjectPOST Project

• Now define a Wallet class:Now define a Wallet class:

public class Wallet{ private float value;public float getTotalMoney(){return value;}public void setTotalMoney(float val){value = val;}public void addMoney(){float deposit){ value += deposit;}public void subtractMoney(float debit){ value -= debit;}}

Page 15: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

POST PorjectPOST Porject

• Now include some code from the Now include some code from the CashierCashier class:class:

payment = 15.95Wallet theWallet = myCustomer.getWallet();if (theWallet.getTotalMoney()) >= payment){ theWallet.subtractMoney(payment);}else ...

Page 16: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

Why Is This Bad?Why Is This Bad?

• Do you just want to give your wallet to the Do you just want to give your wallet to the Cashier? The Cashier is exposed to Cashier? The Cashier is exposed to more more information than it actually needsinformation than it actually needs

• The Cashier knows too much about the The Cashier knows too much about the wallet and can manipulate itwallet and can manipulate it

• The classes The classes Customer, WalletCustomer, Wallet and and CashierCashier are tightly coupled. If you change are tightly coupled. If you change the the WalletWallet class then a change to the class then a change to the other two is probably necessary.other two is probably necessary.

Page 17: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

Try ThisTry This

• What if the wallet was stolen in the store? What if the wallet was stolen in the store? Then call Then call victim.setWallet(null);victim.setWallet(null);??

• Our code assumes a wallet, so you will get a Our code assumes a wallet, so you will get a runtime exception! If you check for null the runtime exception! If you check for null the code starts becoming complicatedcode starts becoming complicated

• Improvement: Rewrite the Improvement: Rewrite the CustomerCustomer class, class, throw out the throw out the getWallet()getWallet() method, but method, but put in a put in a makePayment()makePayment()

Page 18: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

public class customer{...public float makePayment(float amount){ if (myWallet != null){ if (myWallet.getTotalMoney() >= amount){ myWallet.subtractMoney(amount); return amount;} else .. ... }}

Page 19: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

ConclusionConclusion

• CashierCashier doesn’t even know doesn’t even know CustomerCustomer has has a a WalletWallet!!!!

• Now use the Now use the CashierCashier code: code:

payment = 15.95;paidUp = myCustomer.getPayment(payment);if(paidUp == payment) printReceipt(payment);else ...

Page 20: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

Why Is This Better?Why Is This Better?

• Fact: Fact: CustomerCustomer has become more complex has become more complex• But, this is more realistic--But, this is more realistic--CashierCashier asks asks CustomerCustomer for payment; for payment; CashierCashier has no direct has no direct access to the customer’s access to the customer’s WalletWallet

• The class The class WalletWallet can now change and the can now change and the CashierCashier detects no difference. detects no difference. If theIf the Wallet Wallet interface changed, then only interface changed, then only Customer Customer

has to be updated. has to be updated. Code is easier to maintainCode is easier to maintain Changes don’t ripple upChanges don’t ripple up

Page 21: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

The Are DrawbacksThe Are Drawbacks

• CustomerCustomer is more complex, i.e. has more is more complex, i.e. has more methodsmethods But before But before CashierCashier needed to know about the needed to know about the

Wallet, now not.Wallet, now not. ComplexityComplexity has been reduced to where is has been reduced to where is

belongsbelongs• If, e.g. the If, e.g. the Wallet Wallet had a credit card, then had a credit card, then

the method the method getCreditCardNumber();getCreditCardNumber(); returns the cc#, not the returns the cc#, not the WalletWallet

Page 22: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

LoD (weak version)LoD (weak version)

• Law of DemeterLaw of Demeter: A method of an object : A method of an object should only invoke methods from the should only invoke methods from the following kind of objectsfollowing kind of objects itselfitself its parametersits parameters any objects is createsany objects is creates its direct component objectsits direct component objects

• Each object should have only a limited Each object should have only a limited knowledge of other objectsknowledge of other objects

Page 23: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

When and How to ApplyWhen and How to Apply

• Eliminate chained Eliminate chained getget-Statements: e.g. -Statements: e.g. ccnr = ccnr = person.getWallet().getccnr();person.getWallet().getccnr(); should be changed should be changed ccnr = ccnr = person.getCCnr();person.getCCnr(); and let and let personperson worry about the worry about the ccnrccnr..

• Get rid of temps to do the chainingGet rid of temps to do the chaining• Never import what you don’t needNever import what you don’t need

Page 24: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

LoD (strong version)LoD (strong version)

• In addition to LoD, requireIn addition to LoD, require Never access data directly ininheritance--Never access data directly ininheritance--

always use accessors (i.e. always use accessors (i.e. getsgets and and setssets))

Page 25: Lecture 13 Law of Demeter. Cohesion Cohesion: the “glue” that holds a module together. Don’t do things that do not support a common goal Cohesion: the

LoD and Design PatternsLoD and Design Patterns

• Most obvious: LoD implies delegation, Most obvious: LoD implies delegation, because the complexity is put where it because the complexity is put where it belongsbelongs

• Adapter, Proxy and Decorator wrap objects Adapter, Proxy and Decorator wrap objects and so force the user to a more suitable and so force the user to a more suitable interfaceinterface

• Facade hides other classes behind an APIFacade hides other classes behind an API