8-1 By Rick Mercer with help from Object-Oriented Design Heuristics Arthur Riel Addison-Wesley, 1996, ISBN 0-201-6338-X Relationships amongst Objects.

Slides:



Advertisements
Similar presentations
Design Validation CSCI 5801: Software Engineering.
Advertisements

Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
2-May-15 GUI Design. 2 HMI design There are entire college courses taught on HMI (Human-Machine Interface) design This is just a very brief presentation.
GRASP Patterns M Taimoor Khan
CS 106 Introduction to Computer Science I 12 / 04 / 2006 Instructor: Michael Eckmann.
Conversation Form l One path through a use case that emphasizes interactions between an actor and the system l Can show optional and repeated actions l.
Objects First With Java A Practical Introduction Using BlueJ Designing object-oriented programs How to write code in a way that is easily understandable,
Stéphane Ducasse«ChapterNr».1 Arthur Riel Design Heuristics from Object-Oriented Design Heuristics by Arthur Riel Read the Heuristics… –Find reasons why.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Object-Oriented Thinking Chapter 1, Object-Oriented Programming in Java, Timothy Budd, 1998 ICS102 Semester
SOS OOP Fall 2001 Object Oriented Programming in Java Week 1 Read a design Design a small program Extract a design Run a VAJ program Change that program,
Low Coupling High Cohesion
Object-Orientated Design Unit 3: Objects and Classes Jin Sa.
GRASP : Designing Objects with Responsibilities
L6-1-S1Design Heuristics - 1 © M.E. Fayad SJSU -- CmpE Software System Engineering Dr. M.E. Fayad, Professor Computer Engineering Department,
C++ fundamentals.
Domain Modeling (with Objects). Motivation Programming classes teach – What an object is – How to create objects What is missing – Finding/determining.
Object-Oriented Design. From Analysis to Design Analysis Artifacts –Essential use cases What are the problem domain processes? –Conceptual Model What.
GRASP Design Patterns: Designing Objects with Responsibilities
Object Oriented Software Development
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.
Computer Science II 810:062 Section 01 Session 2 - Objects and Responsibilities.
GRASP Principles. How to Design Objects The hard step: moving from analysis to design How to do it? –Design principles (Larman: “patterns”) – an attempt.
CSCI-383 Object-Oriented Programming & Design Lecture 9.
Introduction to Sequence Diagrams
1 Chapter 17 GRASP Design Patterns: Designing Objects with Responsibilities.
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.
1 SAD2 - UML 4 th Lecture Class Diagram in Construction Phase Patterns Case Study Lecturer: Dr Dimitrios Makris
SOEN 6011 Software Engineering Processes Section SS Fall 2007 Dr Greg Butler
Architecture GRASP Realization of use cases in interaction diagrams Design class diagram Design ( how )
1 Responsibility Driven Design Responsibility Driven Design, Rebecca Wirfs Brock, 1990 The Coffee Machine Design Problem, Alistair Cockburn, C/C++ User's.
GRASP: Designing Objects With Responsibilities
Object-Oriented Analysis and Design Mar 11, 2008.
Chapter 17 GRASP: Designing Objects with Responsibilities. 1CS6359 Fall 2011 John Cole.
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.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Object-Oriented Design Part 2
Cohesion and Coupling CS 4311
Class Diagrams Identifying and representing Classes Object Web, Bapayya Choudhary Maganti.
1 Responsibility Driven Design Responsibility Driven Design, Rebecca Wirfs Brock, 1990 The Coffee Machine Design Problem, Alistair Cockburn, C/C++ User's.
GRASP: Designing Objects with Responsibilities
CS 4850: Senior Project Fall 2014 Object-Oriented Design.
Introduction to Unified Modeling Language (UML) By Rick Mercer with help from The Unified Modeling Language User Guide, Grady Booch, James Rumbaugh, Ivar.
1 What is OO Design? OO Design is a process of invention, where developers create the abstractions necessary to meet the system’s requirements OO Design.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
1 By Rick Mercer with help from Object-Oriented Design Heuristics, Arthur Riel Relationships amongst Objects.
1 Class responsibilities & relationships. 2 Responsibilities Responsibilities describe a class’s purpose in terms of its functionality Responsibilities.
1 By Rick Mercer with help from Object-Oriented Design Heuristics, Arthur Riel Coupling / Cohesion.
Object-Oriented Principles Applications to Programming.
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.
Classes and Objects: The Building Blocks of the Object-Oriented Paradigm Presented by Tara Struble.
OO Design Roshan Chitrakar. Analysis to Design Do the RIGHT thing Do the RIGHT thing Requirement Analysis Requirement Analysis Domain Modeling with addition.
ANU COMP2110 Software Design in 2003 Lecture 10Slide 1 COMP2110 Software Design in 2004 Lecture 12 Documenting Detailed Design How to write down detailed.
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
CHAPTER 14 Classes, Objects, and Games XNA Game Studio 4.0.
Creating a GUI Class An example of class design using inheritance and interfaces.
Copyright © Craig Larman All Rights Reserved COMP-350 Object-Oriented Analysis and Design GRASP: Designing Objects with Responsibilities Reference:
Design. 2 The Need for Software Blueprints Knowing an object-oriented language and having access to a library is necessary but not sufficient in order.
Refactoring Agile Development Project. Lecture roadmap Refactoring Some issues to address when coding.
1 COS 260 DAY 12 Tony Gauvin. 2 Agenda Questions? 5 th Mini quiz –Chapter 5 40 min Assignment 3 Due Assignment 4 will be posted later (next week) –If.
GRASP – Designing Objects with Responsibilities
Relationships amongst Objects
Chapter 12: Collaboration Diagram - PART2
Conception OBJET GRASP Patterns
Introduction to Unified Modeling Language (UML)
DESIGN MODEL: USE-CASE REALIZATIONS WITH GRASP PATTERNS
TK2023 Object-Oriented Software Engineering
GRASP Design Patterns: Designing Objects with Responsibilities
Object Oriented System Design Responsibilities
Presentation transcript:

8-1 By Rick Mercer with help from Object-Oriented Design Heuristics Arthur Riel Addison-Wesley, 1996, ISBN X Relationships amongst Objects

8-2  Consider six relationships between objects  Offer some guidelines for better OO design – A few design heuristics – Low coupling and high cohesion Outline

8-3 Relationship Between Objects  Object relationships occur when one object 1.sends messages to an instance variables 2.sends a message to another object 3.is passed as an argument in a message 4.creates another object 5.reference is returned from a message 6.stores a referential attribute A reference to an object needed by other objects –Example: Jukebox stores a reference to a JukeboxAccount stored in a JukeboxAccountCollection

8-4 Object A sends message to Object B  #1 A uses relationship occurs when one object sends a message to another object. Example: – a listener sends an updateUI() message to a JList object private class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { … rollInputField.setText(""); // set text field to blank }  The sender, the new ButtonListener() object, must know the receiver's name: rollInputField

8-5 Example: Cars and Gas Stations  #2 If a Car "contains" a gas station instance variable – send a fillUp message to its own gas station this.fillUp(Exxon126);  If a Car does not "contain" a gas station – how can a Car send a fillUp message?  #3 A Car could be given the name of the gas station ( Exxon126 ) as an argument // aDispatcher object sends this message car[currentCar].fillUp(Exxon126);

8-6 Other uses relationships  #4 Let the car find a gas station on its own – Assume map is a global variable everyone knows myGasStation = map.getNearestGasStation(); myGasStation.fillUp();  #5 Whenever a car needs gas, let the car build it – It will know the name of the object it creates construct a new one in the Cars fillup method – Note: the gas station will be destroyed upon exit

8-7 Who constructs needed objects?  What object creates object X?  Choose an object B to create an X such that: – B contains X – B closely uses X – B has the initializing data for X

8-8 Referential attribute (can be bad)  #6 Store a reference to a gas station that was created elsewhere – Known to some as a referential attribute – This provides access to an entire object that was constructed elsewhere – The car has a reference needed by someone else  Be careful: This can lead to incorrect behavior – Could be better to have just one instance with a global point of reference

8-9 Design Heuristic Riel's Heuristic 4.1 Minimize the number of objects with which another object collaborates Worst case: The design has a collection of simple objects where each one uses all others Could one class contain several smaller objects?

8-10 A Meal Class Wrap 3 Smaller Classes Melon cost() Restaurant Patron Steak cost() Melon cost() Pie cost() Restaurant Patron Steak cost() Pie cost() Meal

8-11 Meal Wrapper Class  Encapsulation makes 4 messages look like one  Containment simplifies things  RestaurantPatron collaborates with one object now, instead of three

8-12 If you have instance variables, use them Containment implies a relationship, mess- ages should be sent to contained objects If no messages are sent to a contained object, it doesn't belong, Put the attribute in the right class  An exception: Container classes – ArrayList, HashMap, TreeMap, and so on, may not send messages to their elements other than equals or compareTo message Their job is to add, find, and remove elements

8-13 Don't use too many instance variables Most of the methods in a class should be using most of the instance variables most of the time If not, perhaps there should be two classes Classes should not contain more objects than a developer can fit in short term memory Maximum should be 7 plus or minus 2 That's about 5 to 9 instance variables

8-14 A class must know what it contains, but the contained class should not know who contains it – It's okay for a bedroom to know it has a clock, but the clock should not be dependent on the bedroom – currentAccount should not send messages to Jukebox – The JukeboxAccountCollection need not know it is contained in an instance of Jukebox All contained objects are loosely coupled –they are not very dependent on each other Contained objects don’t talk to their containers

8-15 Use a Mediator to Coordinate Activities Objects that share lexical scope -- those in the same containment --need not have relationships between them  Consider an ATM that contains a card reader and a display screen – The card reader should not send a message to the display screen better reuse--could use the card reader software for a security entrance without taking the display screen

8-16 Violation Increases Complexity  An ATM may contain – card reader, display screen, and keypad – The ATM should coordinate activities between these three objects Don’t need additional collaborations HaveACard? Card Reader displayPIN() getPIN() Display Keypad ATM

8-17 Coupling  Coupling: A measure of how strongly one class is connected to, has knowledge of, or relies upon other classes – Low coupling: the class is not dependent on many other classes--good – High Coupling: class is dependent on many others--bad A change to one class forces changes in others More difficult to understand a type in isolation Assign responsibilities so that coupling remains low

8-18 Which is the better design?  If a POST object records an instance of Payment, perhaps the POST object constructs Payment  Then POST asks Sale to add the new payment – POST is coupled to Payment in the following design With this design, POST needs to know 2 classes :POSTp : Payment :Sale makePayment()1: create() 2: addPayment(p)

8-19 An alternative design  Try associating Payment with Sale – In both designs, Sale is coupled to Payment – Low coupling favors this 2nd design :POST:Sale :Payment makePayment()1: makePayment() 1.1. create()

8-20 Try to keep coupling low  Common forms of coupling – Class B has an instance of Class X – Class B send a message to an instance of Class X – Class B is a subclass of Class X (inheritance) – Class B implements interface X  So coupling does occur, in any OO program  Dangerous case of high coupling: – Allow one object to use ins. vars. of another type

8-21 Coupling  Hard to say what high coupling is  Will have some coupling: instance variables, one object asks another for help,...

8-22 High Cohesion  Assign responsibilities so that cohesion remains high cohesion: consistency, pulling together  Cohesion: A measure of how strongly related and focused the responsibilities of a class are – High functional cohesion is good – Low cohesion is bad hard to understand hard to reuse hard to maintain fragile; constantly affected by change

8-23 Several types of cohesion  Functional cohesion is when parts of a module are grouped because they all contribute to a single well-defined task of the module  Examples  Tokenizing a string of XML  BankAccount has no blast off method  Any well structured class (String)

8-24 High vs. Low Cohesion  High functional cohesion exists when the elements of a class "all work together to provide some well-bounded behavior" Grady Booch  Examples of low cohesion – One class is responsible for many things in different functional areas Example: Model arranges views, builds menus,... – One class has sole responsibility of one complex task in one functional area Example: Jukebox determines if a song can play, an account may play, play the mp3 by itself, maintain collections with add, find, remove,....

8-25 High Cohesion  A class has moderate responsibilities in one functional area and collaborates with other objects to fulfill tasks: – e.g. PokerDealer coordinates but gets help from a deck of cards that can shuffle and deal cards the player that can figure out what to do next and knows what he or she can bet a view to show poker hands, pot, cards, animations  Small number of methods, highly related functionality, doesn't do too much

8-26 Benefits of High Cohesion  Design is clearer and more easily understood  Maintenance (bug fixes, enhancements, changing business rules) is easier – The fewer classes you touch the better Adele Goldberg  High cohesion can help you attain lower coupling

8-27  The most basic, general principle of assigning responsibilities (behavior/methods) is to – Assign the responsibility to the object that has the information necessary to fulfill it. – “That which has the information, does the work.” – Who decides if the jukebox object can select?  Important skill in OO Design: – Which objects should do what? Find objects Assign responsibilities Information Expert

8-28 Role Play a Scenario Jukebox: Now I need to determine whether or not the current user can play the selected Song. Who is responsible for knowing the playing time of any Song? Song: It seems like I should be responsible for knowing the duration of my Song. For example, it might take 3 minutes and 34 seconds to be completely played. I'll add the responsibility knowPlayTime. Jukebox: Okay, now I should check to make sure the user is able to select this Song before telling the AudioFilePlayer to play it. I seem to remember I cannot simply play a Song without checking on a few things. I know the current JukeboxAccount and the selected Song. What do I do now?

8-29 Alternative #1 JukeBox: So tell me Song, how many minutes and seconds do you require to be played? Song: 3 minutes and 34 seconds. JukeBox: JukeboxAccount, do you have 3 minutes and 34 seconds credit? JukeboxAccount: I'll be responsible for maintaining remaining time credit, so I can answer that, Yes, I have enough credit. JukeBox: JukeboxAccount, have you played fewer than 2 Songs? JukeboxAccount : I have not played 2 songs today. JukeBox: Okay, now we can play the Song. Here it is AudioFilePlayer. AudioFilePlayer : Okay JukeBox, I am willing and able to play this Song. I'll take care of the playTrack(String fileName) responsibility

8-30 Alternative #2 JukeBox: JukeboxAccount, can you play this Song? JukeBoxAccount: It feels as though I should be responsible for maintaining my own time credit, it seems appropriate that I should also know how many Songs I've played today. So I should be able to do some simple calculations to give you the answer you seek. Yes JukeBox, I can play the Song you sent me. I'll add these responsibilities to my CRC card: know how much time credit I have left know how many Songs I've played on this date respond to a message like this: JukeboxAccount.canSelect(currentTrack)

8-31 Which Alternative is better?  Alternative #1 has a higher degree of coupling" – Jukebox needs to know more details about Song and JukeBoxAccount – There were two different message sends in alternative #1 versus a single message send of alternative #2 (canSelect)  Alternative #2 has better cohesion – This means that at least two of the knowledge responsibilities necessary to answer a canSelect message are closely related

8-32 Which is the better design?  Alternative #1 requires Jukebox to know about the internal state of Song and JukeBoxAccount – Violation of "All data should be hidden within its class"  Alternative #2 better delegates responsibility  Alternative #2 has fewer message sends  Here is another OOD guideline to indicate Alternative #2 is a better design: Minimize the number of message sends between a class and its helpers

8-33 Expert Problem: We are trying to determine who should be responsible for some action Solution: Assign the responsibility to the information expert, which is the class with information necessary to fulfill the responsibility

8-34 Collaborative Exercise: Course scheduling  How should we check if a student has the proper prerequisites before adding a course given these three types (Java classes) – Course description, enrollment limit, prerequisites – Student name, address, SS#, courses taken – CourseOffering course number, schedule, room, registrants