Responsibilities. Using several specific design principles to guide OO design decisions.

Similar documents
17. GRASP: Designing Objects with Responsibilities

Information Expert (or Expert)

COMP 6471 Software Design Methodologies

ADVANCED SOFTWARE DESIGN LECTURE 7 GRASP

Principles of Software Construction: Objects, Design and Concurrency. Object-Oriented Design: Assigning Responsibilities.

GRASP: Patterns for. chapter18

Assigning Responsibilities (Patterns of Responsibility Assignment Principles: GRASP)

Principles of Software Construction: Objects, Design, and Concurrency. Assigning Responsibilities to Objects. toad. Jonathan Aldrich Charlie Garrod

Object Analysis & Design in the textbook. Introduction to GRASP: Assigning Responsibilities to Objects. Responsibility-Driven Design

Assigning Responsibilities by Larman

References: Applying UML and patterns Craig Larman

ADVANCED SOFTWARE DESIGN LECTURE 4 GRASP. Dave Clarke

Last Time: Object Design. Comp435 Object-Oriented Design. Last Time: Responsibilities. Last Time: Creator. Last Time: The 9 GRASP Patterns

GRASP Design Patterns A.A. 2018/2019

2 GRASP Patterns and basic OO Design. Roel Wuyts OASS

On to Object-oriented Design

Introduction to Software Engineering (2+1 SWS) Winter Term 2009 / 2010 Dr. Michael Eichberg Vertretungsprofessur Software Engineering Department of

GRASP ing at the First 5 Patterns Principles CSSE 574: Session 3, Part 4

Goal: build an object-oriented model of the realworld system (or imaginary world) Slicing the soup: OOA vs. OOD

CSSE 374: Logical Architecture. Shawn Bohner Office: Moench Room F212 Phone: (812)

What is a Model? Copyright hebley & Associates

Introduction to Software Engineering (2+1 SWS) Winter Term 2009 / 2010 Dr. Michael Eichberg Vertretungsprofessur Software Engineering Department of

Logical Architecture & Design Preliminaries

be used for more than one use case (for instance, for use cases Create User and Delete User, one can have one UserController, instead of two separate

OO Design2. Design Artifacts

Tecniche di Progettazione: Design Patterns

Mapping Designs to Code

Constantinos Constantinides Computer Science and Software Engineering Concordia University Montreal, Canada

COMP 6471 Software Design Methodologies

CTIS 359 Principles of Software Engineering SOFTWARE DESIGN OO(A)D

VEL TECH HIGH TECH Dr. RANGARAJAN Dr. SAKUNTHALA ENGINEERING COLLEGE UNIT 1 UML DIAGRAMS

From Design Patterns: Elements of Reusable Object Oriented Software. Read the sections corresponding to patterns covered in the following slides.

CSSE 374: GRASP ing at the First Five Patterns Principles. Shawn Bohner Office: Moench Room F212 Phone: (812)

Review Software Engineering October, 7, Adrian Iftene

Object-Oriented Design

Object-Oriented Design

Idioms and Design Patterns. Martin Skogevall IDE, Mälardalen University

Design Patterns. An introduction

Software Engineering

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING CS2353-OBJECT ORIENTED ANALYSIS AND DESIGN. Unit-I. Introduction to OOAD

Inheritance. EEC 521: Software Engineering. Dealing with Change. Polymorphism. Software Design. Changing requirements Code needs to be flexible

CSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich

CS6502-OBJECT ORIENTED ANALYSIS AND DESIGN Two Marks Question with Answers Unit-I Introduction to OOAD

Software Design Patterns. Background 1. Background 2. Jonathan I. Maletic, Ph.D.

From designing to coding

OBJECT ORIENTED ANALYSIS AND DESIGN SYLLABUS

Ingegneria del Software Corso di Laurea in Informatica per il Management. Design Patterns part 1

Design Engineering. Overview

ROEVER ENGINEERING COLLEGE DEPARTMENT OF INFORMATION TECHNOLOGY CS2353-OBJECT ORIENTED ANALYSIS AND DESIGN. Unit-I. Introduction to OOAD

Patterns and Testing

Eliminate enterprise software design instability - protect variations! Nickolay Kofanov

Design Patterns. CSC207 Fall 2017

ADVANCED SOFTWARE DESIGN LECTURE 4 SOFTWARE ARCHITECTURE

Object-Oriented Design

Design Patterns. Observations. Electrical Engineering Patterns. Mechanical Engineering Patterns

Plan. Design principles: laughing in the face of change. What kind of change? What are we trying to achieve?

Object-Oriented Design II - GRASP

Design Patterns. Gunnar Gotshalks A4-1

Software Modeling & Analysis

administrivia today UML start design patterns Tuesday, September 28, 2010

Domain Model and Domain Modeling

On to Object-oriented Design

Applying Some Gang of Four Design Patterns CSSE 574: Session 5, Part 3

Designing for Visibility & Mapping to Code CSSE 574: Session 4, Part 3

Design Patterns. CSC207 Winter 2017

Topics in Object-Oriented Design Patterns

Plan. Design principles: laughing in the face of change. What kind of change? What are we trying to achieve?

Design Pattern What is a Design Pattern? Design Pattern Elements. Almas Ansari Page 1

Modellistica Medica. Maria Grazia Pia, INFN Genova. Scuola di Specializzazione in Fisica Sanitaria Genova Anno Accademico

Avancier Methods. Very basic design patterns. It is illegal to copy, share or show this document

Assigning Responsibilities

Presenter: Dong hyun Park

An Introduction to Patterns

Application Architectures, Design Patterns

1 Software Architecture

The Design Patterns Matrix From Analysis to Implementation

Design. Furthermore, it is natural to discover and change some requirements during the design and implementation work of the early iterations.

Creating Class Definitions from Design Class Diagrams: public class SalesLineItem // Java { private int quantity;

CSC7203 : Advanced Object Oriented Development. J Paul Gibson, D311. Design Patterns

Keywords: Abstract Factory, Singleton, Factory Method, Prototype, Builder, Composite, Flyweight, Decorator.

Requirements and Design Overview

Summary of the course lectures

Domain Modeling: Associations and Attributes

Ingegneria del Software Corso di Laurea in Informatica per il Management. Design Patterns part 1

Goals of Lecture. Lecture 27: OO Design Patterns. Pattern Resources. Design Patterns. Cover OO Design Patterns. Pattern Languages of Programming

Object-Oriented Design I

Work groups meeting 3

CPSC 310 Software Engineering. Lecture 11. Design Patterns

Foundations of Software Engineering Design Patterns -- Introduction

Object Oriented Paradigm

Essential Skills for the Agile Developer. Agile. copyright Net Objectives, Inc.

Design Patterns. Hausi A. Müller University of Victoria. Software Architecture Course Spring 2000

Software Design And Modeling BE 2015 (w. e. f Academic Year )

An Introduction to Patterns

Lecture 17: Patterns Potpourri. Copyright W. Howden 1

In this Lecture you will Learn: Design Patterns. Patterns vs. Frameworks. Patterns vs. Frameworks

GRASP 2. CSC 440: Software Engineering Slide #1

OODP Session 5a. Web Page: Visiting Hours: Tuesday 17:00 to 19:00

A Rapid Overview of UML

Model-based Transition from Requirements to High-level Software Design

Transcription:

Designing Objects with Responsibilities Using several specific design principles to guide OO design decisions.

Challenge Old-school advice on OOD After identifying i your requirements and creating a domain model, then add methods to the appropriate classes, and define the messages between the objects to fulfill the requirements. New-school advice: there are consequences to: where we place methods the way objects interact in our design specific principles can help us make these decisions specific principles can help us make these decisions Note: This is not UML! UML is a notation Larman: The critical design tool for software development is a mind well educated in design principles.

Recall: The big picture Object design is part of the larger modeling effort some inputs to modeling: What s been done? How do things relate? How much design modeling to do, and how? What is the output? Domain models, SDDs some outputs from modeling: object design (UML diagrams interaction, class, package) UI sketches and prototypes database models sketches of reports and prototypes

Design of objects Responsibility-driven design (RDD) What are an object s responsibilities? What are an object s roles? What are an object s collaborations? The term is important: We are initially trained to think objects in terms of data structures and algorithms (attributes and operations) RDD shifts this by treating objects as having roles and responsibilities Objects then become: service providers information holders coordinators, controllers interfaces, etc.

What is an object responsibility? Doing doing something itself (creating an object; performing a calculation) l initiating action in other objects controlling and coordinating activities in other objects Knowing knowing about private encapsulated data knowing about related objects knowing about things it can derive or calculate Responsibilities vary in granularity big (hundreds of classes); example: provide access to relational databases small (one method); example: create an instance of Sale

What is an object collaboration? Assumption: responsibilities are implemented by means of methods the larger the granularity of responsibility, the larger the number of methods this may entail an object interacting with itself or with other objects Therefore: fulfilling responsibilities requires collaborations amongst different methods and objects Low representational gap : RDD is a metaphor Objects are modeled as similar to persons / systems with responsibilities Community of collaborating responsible objects

A couple of parenthetical comments Responsibility here implies non-interference This is idealized (i.e., in the real world this is not necessarily true in boundary cases) However it is suitable enough for object design Suitable for programming-in-the-large As opposed to programming-in-the-small This is a qualitative difference: mass of details amount of communication this become overwhelming Practical as opposed to theoretical

GRASP Craig Larman s methodical approach to OO design In essence: a tool to help apply responsibilities to OOD design designed (and meant to be used as) methodical, rational, explainable techniques They are patterns of assigning responsibilities Note: the use of pattern here is slightly different from some that intended by the GoF book Recognizes that responsibility assignment is something already do: UML interaction diagrams are about assigning responsibilities

A bit more about pattern terminology Patterns as applied to architecture: invented by Christopher h Alexander context that of a pattern language for designing spaces used by humans Classic design patterns for software invented by the Gang of Four (GoF) (Gamma, Johnson, Helm, Vlissides) Patterns is now a rather loose term Conferences exist to look at patterns http://hillside.net/plop/2005/ p p Larman has a special meaning for his GRASP patterns

What is a GRASP pattern? A named and well-known problem/solution pair General enough to be applied to new contexts Specific enough to give advice on how to apply it Especially important for novel situations Also comes with a discussion of: trade-offs implementations variations

Specifically GRASP Defines nine basic OO principles basic building blocks for OO designs Meant to be pragmatic Meant to be a learning aid : aids naming the group of ideas aids in presenting insight of ideas aids in remembering basic, classic design ideas Also intended for combination with: a development process (UP) an organizational i metaphor (RDD) a visual modeling notation (UML)

The Nine GRASP Patterns 1. Creator 6. Polymorphism 2. Information Expert 3. Low Coupling 4. Controller 5. High Cohesion 7. Pure Fabrication 8. Indirection 9. Protected Variations

1. GRASP Creator Problem: Who should be responsible for creating a new instance of some class? Example: Who is responsible for creating SalesLineItem? time Sale 1 Sales LineItem quantity Contains 1..* * Described-by 1 Product Description description price itemid Object creation is one of the most common OO activities (However, set aside for now such concerns as Factory Method vs. Abstract Factory ) Creator principle is meant to help us achieve: low coupling increased clarity increased encapsulation increased reusability Recall: We also have a Register class floating about.

Jargon alert: terms and definitions coupling: the degree to which each program module relies on other modules cohesion: a measure of how well the operations in a module work together to provide a specific piece of functionality encapsulation: synonym for information hiding reusability: likelihood a segment of structured code can be used again to add new functionality with slight or no modification

1. GRASP Creator Problem statement: Who should be responsible for creating a new instance of some class? Solution: o Assign class B the responsibility to create an instance of class A if one of these is true (& the more the better) i. B contains or compositely aggregates A. ii. B records A iii. B closely uses A. iv. B has initializing data for A (i.e., B is an Expert with respect to creating A).

1. GRASP Creator time 1 Sale Contains 1..* Sales LineItem quantity * Described-by 1 : Register : Sale makelineitem(quantity) Who is responsible for creating SalesLineItem? create(quantity) Product Description description price itemid : SalesLineItem Sale will contain many SalesLineItem objects Creator GRASP pattern suggests Sale is one object that t could fulfill this responsibility. Consequences: makelineitem becomes a method in Sale. we capture this decision in our UML design-model diagrams

GRASP patterns give you more Each of these patterns comes with: a discussion i section a contraindication section a benefits section l t d tt i i l ti a related patterns or principles section Important! these patterns provide advice on assignment of responsibilities patterns may conflict in their advice there we must exercise some judgment in applying these patterns the extra sections help us with this This is not mechanical work!

1. GRASP Creator Discussion: intent t is to support low coupling (i.e., creator is found that t already needs to be connected to created object) initializing data is sometimes an indicator of a good Creator some object constructors t have complex signatures which objects have the information needed to supply parameter values for such constructors? Contraindications creation can be complex (recycled instances, creating an instance from a family of similar classes) may wish to use Factory Method or Abstract Factory instead in these cases

1. GRASP Creator Benefits: low coupling has already been mentioned why is this good? Rltd Related patterns or principles: il Low Coupling Factory Method and Abstract Factory Whole-Part pattern: defines aggregate objects that support encapsulation of components

Reality Check

2. GRASP Information Expert Problem statement: What is a general principle of assigning responsibilities to objects? Recall: design model may end up very large (hundreds of classes and methods) If assignment of responsibilities is well chosen, result is an easy to understand system Solution: Assign a responsibility to the information expert This expert is the class that has the information needed to fulfill the responsibility

Key idea: ( Clear Statement t t Rule): Start t assigning responsibilities by clearly stating the responsibility.

2. GRASP Information Expert If there are relevant classes in the design model, then look there first for classes time Sale 1 Sales LineItem quantity Contains 1..* * Described-by 1 Product Description description price itemid NextGEN POS will end up with lots of functionality One small part of this is class that knows the grand total of a sale Clear Statement rule could transform this into: Who should be responsible for knowing the grand total of a sale? Which class of objects has the information needed to determine the total? otherwise look into the Domain Model in order to use or expand its representations to suggest the creation of appropriate classes

2. GRASP Information Expert Sale time 1 Sales LineItem quantity Contains 1..* * Described-by 1 Product Description description price itemid t = gettotal :Sale new method time... Sale gettotal() new method

2. GRASP Information Expert Sale t = gettotal 1 *: st = getsubtotal lineitems[ i ] : : Sale SalesLineItem time... gettotal() 1.1: p := getprice() SalesLineItem quantity :Product Description getsubtotal() Product Description time Sale 1 description price itemid Sales LineItem quantity Contains 1..* * Described-by 1 Product Description description price itemid new method getprice()

Comment Notice how the initial assignment of responsibilities drove the design: Result is the identification of several new methods Interaction diagram helped us capture the result Class model entities are also modified Also notice the degree of delegation getsubtotal (vs. getprice and getquantity to supply a multiplication operation)

2. GRASP Information Expert Read text for full details on pattern s: Discussioni Contraindications (important!) Benefits: Information encapsulation low coupling behavior is distributed across classes (i.e., high cohesion) Related Patterns: Low coupling High cohesion

3. GRASP Low Coupling Problem: How can our design support low dependency? low change impact? increased reuse? Solution: Assign a responsibility so that coupling remains low. Use this principle to evaluate alternative assignment of responsibilities.

Key idea: Coupling affects global understanding, di but decisions i about placing responsibility must be made more locally, usually by choosing from amongst alternatives. atives.

Example NextGen POS: dealing with Payments What object should be responsible for associating Payments with Sales? Three objects appear to be involved Real-world domain: Register records a Payment (Creator?) Also in real-world: A Register also records Sales.

Example Suppose we apply our two previous GRASP patterns like so: (Creator) Suggests Register as a candidate for creating Payments. (Information Expert) Register knows about Payments, and therefore associates these with Sales Resulting interaction diagram appears below makepayment() 1: create() : Register p : Payment 2: addpayment(p) :Sale

Example Recall: Our GRASP pattern is to be applied to alternatives. Another approach: (Creator) Suggests Sales creates Payments makepayment() 1: makepayment() : Register :Sale 1.1. create() :Payment

Evaluating Alternatives makepayment() 1: create() : Register p : Payment Which design choice results in lower coupling? makepayment() 2: addpayment(p) : Register 1: makepayment() :Sale 1.1. create() :Sale :Payment

Kinds of Coupling Often applied to types or classes Class X has an attribute referring to Class Y instance Class X objects call on the services of a Class Y object Class X has methods referencing instances of Class Y (i.e., parameters, local variables of Class Y) Class X is a direct or indirect subclass of Class Y Y is an interface, and Class X implements it Note: All of these are needed at some point We are not trying to eliminate coupling, but rather make careful choices

Important contra-indicator There is a least one set of objects and classes to which we must allow our code to be highly-coupled hl ld Java libraries (i.e., javax.swing, java.util) etc. C libraries.net libraries Key features permitting this: these are stable they are widespread

4. GRASP Controller Problem: What first object beyond the UI layer receives and coordinates ( controls ) a system operation? Solution: Assign responsibility to a class based on one of the following: class is root object for overall system (or major subsystem) a new class based on use case name

Context This usually is applied to the actions recorded in our SSDs system events generated by some GUI we do not write to the GUI just yet, but assume some UI layer Therefore we do not have window, view or document classes Be very careful here as we are so tied to GUIs when visualizing applications GUI is meant to delegate tasks to system

Example (NextGen POS) Records-sale-ofsale of Which class of object should be responsible for receiving the enteritem() system event message? Register? POSSystem? These represent overall system, root object, device, or subsystem. ProcessSaleHandler? ProcessSaleSession? (these would be new) These represent a receiver or handler of all system events of a use case scenario. 0..1 Sales LineItem 1..* Contained-in 1 CashPayment Sale * Ledger 1 1 Recordsaccountsfor 1 Logscompleted Captured-on 0..1 1 Customer Product Catalog 1 Store 1 Used-by * Register 1 1 Houses 1..* Contains 1..* Stocks Paid-by 1 1 Is-for 1 3 Works-on 1 1 * 1 Cashier Product Description * Item Describes 1..*

Example NextGen POS Here are the two basic alternatives. System endsale() enteritem() makenewsale() makepayment() makenewreturn() enterreturnitem()...... Register endsale() enteritem() makenewsale() makepayment() makenewreturn() enterreturnitem()... (And how do we choose from amongst them?) system operations discovered during system behavior analysis allocation of system operations during design, using one facade controller System endsale() enteritem() makenewsale() makepayment() enterreturnitem() makenewreturn()...... ProcessSale Handler endsale() enteritem() makenewsale() makepayment() allocation of system operations during design, using several use case controllers... HandleReturns Handler enterreturnitem() makenewreturn()...

Cautions A balance must be striked between having too many controllers and too few More common problem: too few (i.e., bloated controllers ) Example: single controller classes for all events (façade) controller performs many of the events itself rather than delegate work controller maintain a lot of state about the system (e.g., variables and attributes)

5. GRASP High Cohesion Problem: How can we keep objects in our design focused? understandable? manageable? Solution: Assign a responsibility so that cohesion remains high. As with low coupling, use this evaluate alternatives to placing responsibilities in objects

Signs of Low Cohesion Classes that do too many unrelated things or which do too much work Such classes are: hard to comprehend hard to reuse hard to maintain delicate in that any change elsewhere in the system requires many changes in this class In general: the greater the granularity of classes, the lower the cohesion but we do not want to go to the other extreme (i.e., lots and lots of classes, each doing one trivial thing)

Compare and contrast : Register : Sale (Yet again) What class should be responsible for creating a class instance and associating it with a Sale? makepayment() create() addpayment( p ) p : Payment : Register : Sale makepayment() We have two options Which We have two options. Which shows both high cohesion and low coupling? makepayment() create() : Payment

Contra-indicators Simple people-management issues Large class maintained by a single programmer Performance Distributed ib systems Any place where the overhead of invoking an operation is a significant proportion p of performing the operation