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.

Slides:



Advertisements
Similar presentations
Quality of a Class Abstraction: Coupling & Cohesion Michael L. Collard, Ph.D. Department of Computer Science Kent State University.
Advertisements

Review What is a virtual function? What can be achieved with virtual functions? How to define a pure virtual function? What is an abstract class? Can a.
Structured Design. 2 Design Quality – Simplicity “There are two ways of constructing a software design: One is to make it so simple that there are obviously.
Communication between modules, cohesion and coupling
Software Engineering Class design. Class design – ADT Abstract Data Types:  Why use ADT? Hidden implementation details Changes do not affect whole program.
Introduction to Computers and Programming Lecture 11: Introduction to Methods Professor: Evan Korth New York University.
CS 106 Introduction to Computer Science I 11 / 09 / 2007 Instructor: Michael Eckmann.
Introduction to Computers and Programming Introduction to Methods in Java.
Copyright W. Howden1 Lecture 6: Design Evaluation and Intro to OO Design Patterns.
THE OBJECT-ORIENTED DESIGN WORKFLOW Interfaces & Subsystems.
Module: Definition ● A logical collection of related program entities ● Not necessarily a physical concept, e.g., file, function, class, package ● Often.
1 SOFTWARE DESIGN QUALITY COHESION and COUPLING (Part I)
Design Patterns CS is not simply about programming
Criteria for good design. aim to appreciate the proper and improper uses of inheritance and appreciate the concepts of coupling and cohesion.
Computer Science 240 Principles of Software 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 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.
Chapter 9: Coupling & Cohesion Omar Meqdadi SE 273 Lecture 9 Department of Computer Science and Software Engineering University of Wisconsin-Platteville.
Design-Making Projects Work (Chapter7) n Large Projects u Design often distinct from analysis or coding u Project takes weeks, months or years to create.
CSCI-383 Object-Oriented Programming & Design Lecture 9.
Coupling and Cohesion Pfleeger, S., Software Engineering Theory and Practice. Prentice Hall, 2001.
Coupling and Cohesion Source:
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.
SWE © Solomon Seifu ELABORATION. SWE © Solomon Seifu Lesson 12-3 Cohesion.
Chapter 7: High Quality Routines By Raj Ramsaroop.
Object Interconnections CMPS Object Interconnections Past few chapters: focused on individual classes in isolation or classes in parent/child relationships.
Modularity Lecture 4 Course Name: High Level Programming Language Year : 2010.
Design Patterns. Patterns “Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution.
Cohesion and Coupling CS 4311
System Implementation
Coupling & Cohesion CMSC 201- Fall '11. Vocabulary Routine- A programming unit that performs a task, such as a function, procedure, method, or main class.
SWE © Solomon Seifu ELABORATION. SWE © Solomon Seifu Lesson 12-5 Software Engineering Design Goals.
Programming Logic and Design Using Methods. 2 Objectives Review how to use a simple method with local variables and constants Create a method that requires.
Coupling Cohesion Chandan R. Rupakheti Steve Chenoweth (Chapter 18)
Structural Design Patterns
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Object-Oriented Design
BTS430 Systems Analysis and Design using UML Domain Model—Part 2: Associations and Attributes.
1 CSCD 326 Data Structures I Software Design. 2 The Software Life Cycle 1. Specification 2. Design 3. Risk Analysis 4. Verification 5. Coding 6. Testing.
Designing Classes. Software changes Software is not like a novel that is written once and then remains unchanged. Software is extended, corrected, maintained,
Object-Oriented Principles Applications to Programming.
Jump to first page (C) 1998, Arun Lakhotia 1 Design Quality Metrics Arun Lakhotia University of Southwestern Louisiana Po Box Lafayette, LA 70504,
BTS430 Systems Analysis and Design using UML Domain Model—Part 2: Associations and Attributes.
Copyright © Craig Larman All Rights Reserved COMP-350 Object-Oriented Analysis and Design GRASP: Designing Objects with Responsibilities Reference:
Refactoring Agile Development Project. Lecture roadmap Refactoring Some issues to address when coding.
Watching the movie the hard way…. Page 256 – Head First Design Patterns.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Key Principles of Software Architecture and Design (II) adapted from Dave Penny’s.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Slide 1 Good Methods. Slide 2 Cohesion and Coupling l For structured design These software metrics were used extensively Proven to be effective l For.
Lecture 12 Implementation Issues with Polymorphism.
Chapter 9: Coupling & Cohesion Omar Meqdadi SE 273 Lecture 9 Department of Computer Science and Software Engineering University of Wisconsin-Platteville.
3/1/01H-1 © 2001 T. Horton CS 494 Object-Oriented Analysis & Design Evaluating Class Diagrams Topics include: Cohesion, Coupling Law of Demeter (handout)
Programming Logic and Design Fifth Edition, Comprehensive Chapter 7 Using Methods.
Coupling and Cohesion Schach, S, R. Object-Oriented and Classical Software Engineering. McGraw-Hill, 2002.
Coupling and Cohesion Pfleeger, S., Software Engineering Theory and Practice. Prentice Hall, 2001.
Programming Logic and Design Seventh Edition
7. Modular and structured design
Coupling and Cohesion Rajni Bhalla.
Phil Tayco Slide version 1.0 Created Sep 18, 2017
MPCS – Advanced java Programming
Coupling and Cohesion 1.
Cohesion and Coupling Chapter 5, Pfleeger 01/01/10.
Improving the Design “Can the design be better?”
Software Design CMSC 345, Version 1/11.
Programming Logic and Design Fourth Edition, Comprehensive
Software Design Lecture : 9.
Software Design Lecture : 11.
Cohesion and Coupling.
Presentation transcript:

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 “glue” that holds a module together. Don’t do things that do not support a common goal As with coupling there are degrees of cohesion As with coupling there are degrees of cohesion Listed from most to least desirable Listed from most to least desirable

Taxonomy of Cohesion Data Cohesion: A module implements a data abstraction Data Cohesion: A module implements a data abstraction Functional Cohesion: All elements are dedicated to performing a single function Functional Cohesion: All elements are dedicated to performing a single function Sequential Cohesion: Calling the elements in a specific order Sequential Cohesion: Calling the elements in a specific order Communication Cohesion: All elements operate on the same input/output data Communication Cohesion: All elements operate on the same input/output data

Taxonomy of Cohesion (ctd) Temporal Cohesion: Elements are invoked at or near the same time Temporal Cohesion: Elements are invoked at or near the same time Logical Cohesion: If tasks the elements perform are conceptually related Logical Cohesion: If tasks the elements perform are conceptually related Coincidental Cohesion: If the tasks the elements perform are totally unrelated Coincidental Cohesion: If the tasks the elements perform are totally unrelated

Functional Cohesion Elements perform tasks in a specific domain for a specific purpose Elements perform tasks in a specific domain for a specific purpose Meyers: “The purpose of an informational strength module is to hide some concept, data structure or resource in a single module” Meyers: “The purpose of an informational strength module is to hide some concept, data structure or resource in a single module” class bakeCake{ void addIngredients(){...} void mixBatter(){...} void bake(){...} }

Sequential Cohesion The output from one element becomes the input for another The output from one element becomes the input for another The previous example is sequentially cohesive, because the order and tasks performed are sequentially determined The previous example is sequentially cohesive, because the order and tasks performed are sequentially determined Bad for reusability and maintainability Bad for reusability and maintainability

Communication Cohesion Share portions of a common data structure or parameters Share portions of a common data structure or parameters Example:Calculate employee statistics and write monthly paycheck Example:Calculate employee statistics and write monthly paycheck Problems Problems  Wide interface  Bad reusability and maintenenace Cure: Isolate each sharing member into a separate module Cure: Isolate each sharing member into a separate module

Temporal Cohesion Tasks are performed at about the same time Tasks are performed at about the same time E.g. Initialize a program at boot time E.g. Initialize a program at boot time Main problem: Multiple functions, elements are not necessarily cohesive Main problem: Multiple functions, elements are not necessarily cohesive class initStuff{ void initMemory(){...} void initDisk(){...} void initPrinter{...} }

Logical Cohesion Tasks are conceptually related, but no data or control connection Tasks are conceptually related, but no data or control connection Problems: Problems:  Wide Interface  Multiple Functions class areaUtils{ double squareArea(){...} double triangArea(){...} double circleArea(){...} }

Coincidental Cohesion The worst kind: the “kitchen sink”. No real reason for grouping The worst kind: the “kitchen sink”. No real reason for grouping Big offender one-class Java Big offender one-class Java Problems: Problems:  Multiple functionality  Result of poor maintenance class myStuff{ void initPrinter(){...} double calculateTaxes(){...} Date getDate(){...}

Also: Procedural Cohesion Associate elements on the basis of algorithmic or procedural relationships Associate elements on the basis of algorithmic or procedural relationships First do A then B, hence put them together in one method or element First do A then B, hence put them together in 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);} }

Law of Demeter (LoD) Good technique for reducing coupling between objects in programming code Good technique for reducing coupling between objects in programming code Proven “Industrial Strength”. i.e. used in major SW projects to reduce maintenance costs Proven “Industrial Strength”. i.e. used in major SW projects to reduce maintenance costs Let’s look at an example Let’s look at an example

POST 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:]

POST 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;} }

POST Porject Now include some code from the Cashier class: Now include some code from the Cashier class: payment = Wallet theWallet = myCustomer.getWallet(); if (theWallet.getTotalMoney()) >= payment){ theWallet.subtractMoney(payment);} else...

Why Is This Bad? Do you just want to give your wallet to the Cashier? The Cashier is exposed to more information than it actually needs Do you just want to give your wallet to the Cashier? The Cashier is exposed to more information than it actually needs The Cashier knows too much about the wallet and can manipulate it The Cashier knows too much about the wallet and can manipulate it The classes Customer, Wallet and Cashier are tightly coupled. If you change the Wallet class then a change to the other two is probably necessary. The classes Customer, Wallet and Cashier are tightly coupled. If you change the Wallet class then a change to the other two is probably necessary.

Try This What if the wallet was stolen in the store? Then call victim.setWallet(null); ? What if the wallet was stolen in the store? Then call victim.setWallet(null); ? Our code assumes a wallet, so you will get a runtime exception! If you check for null the code starts becoming complicated Our code assumes a wallet, so you will get a runtime exception! If you check for null the code starts becoming complicated Improvement: Rewrite the Customer class, throw out the getWallet() method, but put in a makePayment() Improvement: Rewrite the Customer class, throw out the getWallet() method, but put in a makePayment()

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

Conclusion Cashier doesn’t even know Customer has a Wallet !! Cashier doesn’t even know Customer has a Wallet !! Now use the Cashier code: Now use the Cashier code: payment = 15.95; paidUp = myCustomer.getPayment(payment); if(paidUp == payment) printReceipt(payment); else...

Why Is This Better? Fact: Customer has become more complex Fact: Customer has become more complex But, this is more realistic-- Cashier asks Customer for payment; Cashier has no direct access to the customer’s Wallet But, this is more realistic-- Cashier asks Customer for payment; Cashier has no direct access to the customer’s Wallet The class Wallet can now change and the Cashier detects no difference. The class Wallet can now change and the Cashier detects no difference.  If the Wallet interface changed, then only Customer has to be updated.  Code is easier to maintain  Changes don’t ripple up

The Are Drawbacks Customer is more complex, i.e. has more methods Customer is more complex, i.e. has more methods  But before Cashier needed to know about the Wallet, now not.  Complexity has been reduced to where is belongs If, e.g. the Wallet had a credit card, then the method getCreditCardNumber(); returns the cc#, not the Wallet If, e.g. the Wallet had a credit card, then the method getCreditCardNumber(); returns the cc#, not the Wallet

LoD (weak version) Law of Demeter: A method of an object should only invoke methods from the following kind of objects Law of Demeter: A method of an object should only invoke methods from the following kind of objects  itself  its parameters  any objects is creates  its direct component objects Each object should have only a limited knowledge of other objects Each object should have only a limited knowledge of other objects

When and How to Apply Eliminate chained get -Statements: e.g. ccnr = person.getWallet().getccnr(); should be changed ccnr = person.getCCnr(); and let person worry about the ccnr. Eliminate chained get -Statements: e.g. ccnr = person.getWallet().getccnr(); should be changed ccnr = person.getCCnr(); and let person worry about the ccnr. Get rid of temps to do the chaining Get rid of temps to do the chaining Never import what you don’t need Never import what you don’t need

LoD (strong version) In addition to LoD, require In addition to LoD, require  Never access data directly ininheritance-- always use accessors (i.e. gets and sets )

LoD and Design Patterns Most obvious: LoD implies delegation, because the complexity is put where it belongs Most obvious: LoD implies delegation, because the complexity is put where it belongs Adapter, Proxy and Decorator wrap objects and so force the user to a more suitable interface Adapter, Proxy and Decorator wrap objects and so force the user to a more suitable interface Facade hides other classes behind an API Facade hides other classes behind an API