On to Object-oriented Design

Similar documents
On to Object-oriented Design

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

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

ADVANCED SOFTWARE DESIGN LECTURE 7 GRASP

Information Expert (or Expert)

COMP 6471 Software Design Methodologies

GRASP: Patterns for. chapter18

Assigning Responsibilities (Patterns of Responsibility Assignment Principles: GRASP)

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

Assigning Responsibilities by Larman

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

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

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

17. GRASP: Designing Objects with Responsibilities

References: Applying UML and patterns Craig Larman

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

ADVANCED SOFTWARE DESIGN LECTURE 4 GRASP. Dave Clarke

2 GRASP Patterns and basic OO Design. Roel Wuyts OASS

Domain Model and Domain Modeling

GRASP Design Patterns A.A. 2018/2019

Mapping Designs to Code

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

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

OO Design2. Design Artifacts

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

Object-Oriented Design

Object-Oriented Design

Tecniche di Progettazione: Design Patterns

COMP 6471 Software Design Methodologies

Software Modeling & Analysis

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

Modeling Dynamic Behavior

Modeling Dynamic Behavior

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

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

Logical Architecture & Design Preliminaries

Software Engineering

Design Engineering. Overview

Domain Modeling- 2. Generalization

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

ADVANCED SOFTWARE DESIGN LECTURE 4 SOFTWARE ARCHITECTURE

CSE 403 Lecture 8. UML Class Diagrams. Thanks to Marty Stepp, Michael Ernst, and other past instructors of CSE 403

GRASP 2. CSC 440: Software Engineering Slide #1

Produced by. Agile Software Development. Eamonn de Leastar

From designing to coding

Principles of Software Construction: Objects, Design, and Concurrency

Assigning Responsibilities

Domain Modeling: Associations and Attributes

Single Responsibility Principle (SRP)

Domain Modeling. CSSE 574: Week 1, Part 3. Steve Chenoweth Phone: Office (812) Cell (937)

Chapter 1: Principles of Programming and Software Engineering

Eliminate enterprise software design instability - protect variations! Nickolay Kofanov

Lethbridge/Laganière 2005 Chapter 9: Architecting and designing software 6

Object-Oriented Design

Object- Oriented Design with UML and Java Part I: Fundamentals

What is a Model? Copyright hebley & Associates

Relationships amongst Objects

Patterns and Testing

Topic : Object Oriented Design Principles

4 Software models. often more than what people can handle not necessary to know all details at all times

Expanding Our Horizons. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 9 09/25/2011

Pearson Education 2005 Chapter 6 (Maciaszek - RASD 2/e) 2

PROCESS DEVELOPMENT METHODOLOGY The development process of an API fits the most fundamental iterative code development

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

SE203b: OO Design for Software Engineers. Office: TEB349, Ext

Operations Contracts and Preliminaries on Design

Object Oriented Analysis and Design CS6502

MechEng SE3 Lecture 7 Domain Modelling

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

CS112 Lecture: Defining Instantiable Classes

Outline. Software Rots

BCS Higher Education Qualifications. Diploma in IT. Object Oriented Programming Syllabus

CS 307: Software Engineering. Lecture 10: Software Design and Architecture

Review of Basic Software Design Concepts. Fethi Rabhi SENG 2021

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

OBJECT ORIENTED ANALYSIS AND DESIGN SYLLABUS

Principles of Software Construction: Objects, Design and Concurrency. Just enough UML. toad

Software Design and Analysis CSCI 2040

Object-Oriented Analysis and Design Using UML (OO-226)

PROCESSI DI PRODUZIONE E GESTIONE DEL SOFTWARE. Analysis and Design with UML. Paola Turci

Credit where Credit is Due. Lecture 4: Fundamentals of Object Technology. Goals for this Lecture. Real-World Objects

Object Relationships

Course "UML and Design Patterns" of module "Software Engineering and Design", version February 2011 (X)

Applying UML & Patterns (3 rd ed.) Chapter 15

Object-Oriented Design I

Software Service Engineering

Client Code - the code that uses the classes under discussion. Coupling - code in one module depends on code in another module

SonarJ White Paper. Sonar stands for Software and Architecture. It is meant to support software developers and architects in their daily work.

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

CS6502- OBJECT ORIENTED ANALYSIS AND DESIGN UNIT I

Example: Fibonacci Numbers

Lecture Chapter 2 Software Development

Software Design Fundamentals. CSCE Lecture 11-09/27/2016

Object-Oriented Functional Analysis and Design for POS Example

Problem Solving Object Oriented Design Systems Analysis

Object-Oriented Design II - GRASP

Topics. Designing the program. Chapter 9 Program and Transaction Design. (c) Addison Wesley Chapter 9

CompSci 125 Lecture 07. Chapter 4: Object-Oriented Development

ECE 122. Engineering Problem Solving with Java

Recap : UML artefacts. Black Box Requirements. Functional Specification. System. System. Test. Design. System. System. Development.

Transcription:

Dr. Michael Eichberg Software Technology Group Department of Computer Science Technische Universität Darmstadt Introduction to Software Engineering On to Object-oriented Design

Object-oriented Design 2 A popular way of thinking about the design of software objects and also large scale components is in terms of responsibilities, roles and collaborations.

Object-oriented Design 3 Sales LineItem quantity 1..* Contained-in Records-sale-of 0..1 1 Item * loop :Cashier :System makenewsale [more items] enteritem(itemid, quantity) description, total Sale date time Paid-by 1 0..1 Captured-on 1 Store address name Stocked-in endsale makepayment (amount) Payment amount 1 Register Houses Which class / object should have which responsibility?

Object-oriented Design Object-oriented Design 4 Artifacts that are used as input for the object-oriented design a simple domain (analysis / conceptual) model does exist descriptions of use-cases (user stories) which are under development in the current iterative step we do have a system sequence diagram Next steps: Build interaction diagrams for system operations of the use-cases at hand by applying guidelines and principles for assigning responsibilities

Responsibility for System Operations Object-oriented Design 5 During system behavior analysis (e.g. of the POS system), system operations are assigned to a conceptual class (e.g. System) Does not imply that there will be a class System in the design. A controller class is assigned to perform the system operations System endsale() enteritem() makepayment()

Responsibility for System Operations Object-oriented Design 6 During system behavior analysis (e.g. of the POS system), system operations are assigned to a conceptual class (e.g. System) Who should be responsible for handling system operations? What first object beyond the UI layer receives and coordinates a system operation? Does not imply that there will be a class System in the design. A controller class is assigned to perform the system operations System endsale() enteritem() makepayment()

Responsibility for System Operations Object-oriented Design 7 During system behavior analysis (e.g. of the POS system), system operations are assigned to a conceptual class (e.g. System) Who should be responsible for handling system operations? What first object beyond the UI layer receives and coordinates a system operation? Does not imply that there will be a class System in the design. A controller class is assigned to perform the system operations The system operations become the starting messages entering the controllers for domain layer interaction diagrams. System endsale() enteritem() makepayment()

Interaction Diagrams for System Operations Object-oriented Design 8 Create a separate diagram for each system operation in the current development cycle Use the system operation, e.g., enteritem(), as starting message If a diagram gets complex, split it into smaller diagrams Distribute responsibilities among classes: from the conceptual model and may be others added during object design The classes will collaborate for performing the system operation. based on the description of the behavior of system operations

Foundations of Object-oriented Design

Responsibility Responsibility 10 R. Martin Each responsibility is an axis of change. When the requirements change, a change will manifest through a change in responsibility amongst the classes. If a class has multiple responsibilities, it has multiple reasons to change.

Object-oriented Design - Responsibility 11 Assigning Responsibility to classes is one of the most important activities during the design. Patterns, idioms, principles etc. help in assigning the responsibilities. US Department of Defense

Object-oriented Design - Responsibility 12 In Responsibility-driven Design (RDD) we think of software objects as having responsibilities. The responsibilities are assigned to classes of objects during object-design.

Responsibilities are related to the obligations or behavior of an object in terms of its role. We can distinguish two basic types of responsibilities. Doing responsibilities Doing something itself E.g. creating an object or doing a calculation. Initiating action in other objects Object-oriented Design - Responsibility 13 Controlling and coordinating activities in other objects Example: a Sale object is responsible for creating SalesLineItem objects Knowing responsibilities Knowing about private encapsulated data Knowing about related objects Knowing about things it can derive or calculate Example: a Sale is responsible for knowing its total

Responsibilities are assigned to objects by using methods of classes to implement them. Object-oriented Design - Responsibility To implement a responsibility, methods act alone or collaborate with other methods (of other objects): 1 method in 1 object, 5 methods in 1 object, 50 methods across 10 objects depending on the granularity of the }responsibility 14 A responsibility is not the same thing as a method.

Responsibilities are assigned to objects by using methods of classes to implement them. Examples: Providing access to data bases may involve dozens of classes Print a sale may involve only a single or a few methods Object-oriented Design - Responsibility Assigning responsibilities to classes is one of the most important activities during the design. Patterns, idioms, principles etc. help in assigning the responsibilities. 15 A responsibility is not the same thing as a method.

Object-oriented Design - Responsibility 16????? How does one determine the assignment of responsibilities to various objects?????

Object-oriented Design - Responsibility 17 How does one determine the assignment of responsibilities to various objects? There is a great variability in responsibility assignment : Hence, good and poor designs, beautiful and ugly designs, efficient and inefficient designs. Poor choices lead to systems which are fragile and hard to maintain, understand, reuse, or extend!

Coupling Object-oriented Design - Coupling 18 Coupling measures the strength of dependence between classes and packages. Class C1 is coupled to class C2 if C1 requires C2 directly or indirectly. A class that depends on 2 other classes has a lower coupling than a class that depends on 8 other classes Coupling is an evaluative principle!

Common Forms of Coupling in Java Object-oriented Design - Coupling 19 Type X has an attribute that refers to a type Y instance or type Y itself class X{ private Y y = } class X{ private Object o = new Y(); } A type X object calls methods of a type Y object class Y{f(){;}} class X{ X(){new Y.f();}} Type X has a method that references an instance of type Y (E.g. by means of a parameter, local variable, return type, ) class Y{} class X{ X(y Y){ }} class X{ Y f(){ }} class X{ void f(){object y = new Y();}} Type X is a subtype of type Y class Y{}... class X extends Y{}

Coupling in Java - Exemplified Coupling 20 Class QuitAction is coupled with: ActionListener ActionEvent java.lang.override java.lang.system java.lang.object package de.tud.simpletexteditor; import java.awt.event.actionevent; import java.awt.event.actionlistener; public class QuitAction implements ActionListener { @Override public void actionperformed(actionevent e) { System.exit(0); } } Example Source Code

Coupling Object-oriented Design - Coupling 21 High Coupling A class with high coupling is undesirable, because... changes in related classes may force local changes harder to understand in isolation harder to reuse because its use requires the inclusion of all classes it is dependent upon...

Coupling Object-oriented Design - Coupling 22... Low Coupling Low coupling supports design of relatively independent, hence more reusable, classes Generic classes, with high probability for reuse, should have especially low coupling Very little or no coupling at all is also not desirable Central metaphor of OO: a system of connected objects that communicate via messages Low coupling taken to excess results in active objects that do all the work

Coupling Object-oriented Design - Coupling 23... Low Coupling Low coupling supports design of relatively independent, hence more reusable, classes Generic classes, with high probability for reuse, should have especially low coupling High coupling to stable elements and to pervasive elements is seldom a problem. Very little or no coupling at all is also not desirable Central metaphor of OO: a system of connected objects that communicate via messages Low coupling taken to excess results in active objects that do all the work

Coupling Object-oriented Design - Coupling 24... Low Coupling Low coupling supports design of relatively independent, hence more reusable, classes Generic classes, with high probability for reuse, should have especially low coupling Beware: the quest for low coupling to achieve reusability in a future (mythical!) project may lead to needless complexity and increased project cost. Very little or no coupling at all is also not desirable Central metaphor of OO: a system of connected objects that communicate via messages Low coupling taken to excess results in active objects that do all the work

Cohesion Object-oriented Design - Cohesion 25 Cohesion measures the strength of the relationship amongst elements of a class All operations and data within a class should naturally belong to the concept that the class models Cohesion is an evaluative principle!

Cohesion in Java - Exemplified Cohesion 26 Analysis of the cohesion of SimpleLinkedList public class SimpleLinkedList { private final Object value; private final SimpleLinkedList next; the constructor uses both fields head uses only the field value tail uses only next head and tail are simple getters; they do not mutate the state } public SimpleLinkedList( Object value, SimpleLinkedList next ) { this.value = value; this.next = next; } public Object head() { return value; } public SimpleLinkedList tail() { return next; } Example Source Code

Cohesion in Java - Exemplified Cohesion 27 Analysis of the cohesion of ColorableFigure import java.awt.color; abstract class ColorableFigure implements Figure { linecolor is used only by its getter and setter fillcolor is used only by its getter and setter linecolor and fillcolor have no interdependency } private Color linecolor = Color.BLACK; private Color fillcolor = Color.BLACK; public Color getlinecolor() { return linecolor; } public void setlinecolor(color c) { } linecolor = c; public Color getfillcolor() { return fillcolor; } public void setfillcolor(color c) { this.fillcolor = c; } Example Source Code

Types of Cohesion Object-oriented Design - Cohesion 28 Coincidental No meaningful relationship amongst elements of a class. Logical cohesion (functional cohesion) Elements of a class perform one kind of a logical function. E.g., interfacing with the POST hardware. Temporal cohesion All elements of a class are executed together.

Object-oriented Design - Cohesion 29 Responsibility To keep design complexity manageable, assign responsibilities while maintaining high cohesion. Cohesion

Low Cohesion Object-oriented Design - Cohesion 30 Classes with low cohesion are undesirable, because they are... hard to comprehend, hard to reuse, hard to maintain - easily affected by change... Classes with high cohesion can often be described by a simple sentence.

Low Cohesion Object-oriented Design - Cohesion 31 Classes with low cohesion... often represent a very large-grain abstraction have taken responsibility that should have been delegated to other objects Classes with high cohesion can often be described by a simple sentence.

Design needs principles. Object-oriented Design 32

Object-oriented Design 33 reason to change. I.e. a responsibility is primarily a reason for change. A class should have only one! The Single Responsibility Principle Agile Software Development; Robert C. Martin; Prentice Hall, 2003

Example: a Rectangle Class The Single Responsibility Principle Object-oriented Design 34 Computational Geometry Application Rectangle +draw() +area() : double Graphical Application GUI Does the Rectangle class have? a single responsibility or does it have multiple responsibilities

Example: a Rectangle Class The Single Responsibility Principle Object-oriented Design 35 Computational Geometry Application Rectangle +draw() +area() : double Graphical Application GUI The Rectangle class has multiple responsibilities: Calculating the size of a rectangle; a mathematical model To render a rectangle on the screen; a GUI related functionality Do you see any problems?

Example: a Rectangle Class The Single Responsibility Principle Object-oriented Design 36 Computational Geometry Application Rectangle +draw() +area() : double Graphical Application GUI Problems due to having multiple responsibilities: Reuse of the Rectangle class (e.g. in a math package) is hindered due to the dependency on the GUI package (GUI classes have to be deployed along with the Rectangle class) A change in the Graphical Application that results in a change of Rectangle requires that we retest and redeploy the Rectangle class in the context of the Computational Geometry Application

Example: Rectangle classes with single responsibilities The Single Responsibility Principle Object-oriented Design 37 Computational Geometry Application Graphical Application Geometric Rectangle +area() : double +draw() Rectangle GUI The solution is to separate the functionality for drawing a rectangle and the functionality for doing calculations are separated. Coupling? Cohesion?

Example: Handling Persistence The Single Responsibility Principle Object-oriented Design 38 Persistence Subsystem Employee +CalculatePay() +Store(...) Do we need to change the Employee class?

Example: Handling Persistence The Single Responsibility Principle Object-oriented Design 39 Persistence Subsystem Employee +CalculatePay() +Store(...) Two responsibilities: Business functionality Persistence related functionality Do we need to change the Employee class?

Orthogonality Object-oriented Design 40 Two or more things are orthogonal if changes in one do not affect any of the others; e.g. if a change to the database code does not affect your GUI code, both are said to be orthogonal. z y if z changes, x and y remain unchanged x Andrew Hunt and David Thomas; The Pragmatic Programmer; Addison-Wesley, 2000

GRASP General Responsibility Assignment Principles The following slides make extensive use of material from: Applying UML and Patterns, 3rd Edition; Craig Larman; Prentice Hall

Fundamental GRASPrinciples... GRASPrinciples 42 Controller Creator (Information)Expert The GRASPrinciples are a learning aid....

GRASP - Controller - Candidates GRASP - Controller 43 During system behavior analysis (e.g. of the POS system), system operations are assigned to a conceptual class (e.g. System) Does not imply that there will be a class System in the OO design. A class is assigned to perform these operations. System endsale() enteritem() makepayment() Who should be responsible for handling system? operations? What first object beyond the UI layer receives and coordinates a system operation?

GRASP - Controller - Candidates GRASP - Controller 44 Façade controller A class that represents the overall system or business Candidates for assigning controller responsibility. Use Case controller A class that represents an artificial handler of all events of a use case enteritem(itemid,quantity) enteritem(itemid,quantity) enteritem(itemid,quantity) enteritem(itemid,quantity) :??? :POST :Register :ProcessSaleHandler Real world actor Facade: overall system Use-case handler

GRASP - Controllers and High Cohesion GRASP - Controller 45 Façade controllers are suitable when there are only a few system events Use Case controller These are not domain objects, these are artificial constructs to support the system. Good when there are many system events across several processes Possible to maintain state for the use case, e.g., to identify out-of-sequence system events: a makepayment before an endsale operation

GRASP - Controllers and Responsibility GRASP - Controller 46 A controller should mostly coordinate activities Delegate to other objects work that needs to be done Signs of a bloated controller: Receives all system events Performs all tasks itself without delegating Has many attributes and maintains significant information about the domain Duplicates information found in other objects Split a bloated controller into use case controllers - likely to help in maintaining low coupling and high cohesion.

GRASP - Controllers and Presentation Layer GRASP - Controller 47 UI objects and the UI layer should not have the responsibility for handling system events Examples that do not qualify as controllers: Window, Menu Item, Sensor,... System operations should be handled by objects belonging to the domain layer This increases the reuse potential; encapsulation of the business process.

GRASP - Controllers and Presentation Layer Bad Design vs. Good Design A user-interface-as-controller design GRASP - Controller 48 reduces the opportunity to reuse domain process logic in future applications it is bound to a particular interface that is seldom applicable in other applications Placing system operation responsibility in a domain object controller makes it easier... to unplug the interface layer and use a different interface technology E.g. in case of multi-channel application. to run the system in an off-line batch mode

GRASP - Controllers and Presentation Layer Bad Design GRASP - Controller 49 Process Sale Presentation UI Layer UPC Quantity Balance :Cashier presses button Enter Item End Sale Make Payment actionperformed(actionevent) Application Logic Domain Layer :SaleJFrame Implementation of Business Logic 1: makelineitem(...) :Sale

GRASP - Controllers and Presentation Layer Good Design GRASP - Controller 50 Process Sale Presentation UI Layer UPC Quantity Balance :Cashier presses button Enter Item End Sale Make Payment :SaleJFrame actionperformed(actionevent) Application Logic Domain Layer Controller :Register 1: enteritem(itemid,quantity) 1.1: makelineitem(...) :Sale

GRASP - Controllers - Summary GRASP - Controller 51 System endsale() enteritem() makepayment() Register... endsale() enteritem(...) makenewsale(...) makepayment(...) System operations discovered during system behavior analysis. Allocation of system operations during design. System operations - identified during analysis - are assigned - during design - to one or more non-ui classes called controllers that define an operation for each system operation

Example Designing makenewsale of the ProcessSale Use Case GRASP - Case Study 52...... Preconditions None System Operation Contract a Sale instance s was created Instance creation Postconditions s was associated with the Register Association formed the attributes of s are initialized

Example Designing makenewsale of the ProcessSale Use Case Choosing the Controller for makenewsale GRASP - Case Study 53 What first object beyond the UI layer receives and coordinates a system operation? A controller is the first object beyond the UI layer that is responsible for receiving or handling a system operation message. Controller

Example Designing makenewsale of the ProcessSale Use Case Choosing the Controller for makenewsale GRASP - Case Study 54 A class that represents the overall system, a root object, a specialized device, or a major subsystem: a Store object representing the entire store a Register object (a specialized device that the software runs on) Represents a receiver or handler of all system events of a use case (artificial object): a ProcessSaleHandler object a ProcessSaleSession object Sales LineItem quantity Contained-in Sale date time Paid-by 1..* 1 Payment amount 0..1 Records-sale-of 0..1 1 Captured-on 1 Item * 1 Store address name Register Stocked-in Houses Possible Alternatives (as Suggested by Controller)

Example Designing makenewsale of the ProcessSale Use Case Choosing the Controller for makenewsale GRASP - Case Study 55 Reasoning Register would represent a device façade controller Recall from the discussion of Controller: Device façade controllers are suitable when there are only a few system events... Sales LineItem quantity Contained-in Sale date time Paid-by 1..* 1 Payment amount 0..1 Records-sale-of 0..1 1 Captured-on 1 Item * 1 Store address name Register Stocked-in Houses Possible Alternatives (as Suggested by Controller)

Example Designing makenewsale of the ProcessSale Use Case Choosing the Controller for makenewsale GRASP - Case Study 56 Reasoning Choosing a Store object would lead to low cohesion If we continue using Store for everything. Choosing Store results in a high representational gap Sales LineItem quantity Contained-in Sale date time Paid-by 1..* 1 Payment amount 0..1 Records-sale-of 0..1 1 Captured-on 1 Item * 1 Store address name Register Stocked-in Houses Possible Alternatives (as Suggested by Controller)

Example Designing makenewsale of the ProcessSale Use Case Choosing the Controller for makenewsale GRASP - Case Study 57 Use-case controllers (ProcessSaleHandler, ProcessSaleSession) are good when... there are many system events across several processes, it is necessary to identify out-of-sequence system events. Reasoning Sales LineItem quantity Contained-in Sale date time Paid-by 1..* 1 Payment amount 0..1 Records-sale-of 0..1 1 Captured-on 1 Item * 1 Store address name Register Stocked-in Houses Possible Alternatives (as Suggested by Controller)

Example Designing makenewsale of the ProcessSale Use Case Choosing the Controller for makenewsale GRASP - Case Study 58 Conclusion Register would represent a device façade controller. Device façade controllers are suitable when there are only a few system events... Choosing Store results in low cohesion and a high representational gap. Use-case controller (e.g. ProcessSaleHandler, ProcessSaleSesion) Sales LineItem quantity Contained-in Sale date time Paid-by 1..* 1 Payment amount 0..1 Records-sale-of 0..1 1 Captured-on 1 Item * 1 Store address name Register Stocked-in Houses Possible Alternatives (as Suggested by Controller)

Example Choosing the Controller for the other System Operations System Sequence Diagram :Cashier Process Sale Scenario makenewsale :System GRASP - Case Study Interaction with the domain layer object Register (as suggested by the Controller pattern) 59 loop [more items] enteritem(itemid, quantity) makenewsale :Register description, price, total enteritem :Register endsale endsale :Register total with taxes UI Layer makepayment Domain Layer :Register makepayment (amount) change due, receipt Apply the same reasoning!

GRASP - Information Expert GRASP - Information Expert 60 What is the most basic, general principle of responsibility assign? Assign a responsibility to an information expert, i.e., to a class that has the information needed to fulfill that responsibility.

GRASP - Information Expert - Example Calculating the Grand Total GRASP - Information Expert 61 Sale time 1 Contains 1..* Sales LineItem quantity Described-by * 1 Product Description Given this conceptual model, who should be responsible for calculating the grand total of a sale?

GRASP - Information Expert - Example Calculating the Grand Total GRASP - Information Expert 62 Sale time Given this conceptual model, Contains 1 1..* Sales LineItem quantity Described-by * 1 Product Description who should be responsible for calculating the grand total of a sale? Which class has the information needed for calculating the grand total, i.e., knowledge of all SalesLineItems, and their subtotals?

GRASP - Information Expert - Example Calculating the Grand Total GRASP - Information Expert 63 Sale time Given this conceptual model, Contains 1 1..* Sales LineItem quantity Described-by * 1 Product Description who should be responsible for calculating the grand total of a sale? Which class has the information needed for calculating the grand total, i.e., knowledge of all SalesLineItems, and their subtotals? The Sale object possesses the knowledge about all SaleLineItems. Hence, Sale will be assigned the responsibility.

GRASP - Information Expert - Example Calculating the Sub Total GRASP - Information Expert 64 Sale time 1 total() :Sale Contains 1..* Sales LineItem quantity Described-by * 1 Product Description price Which class has the information needed for calculating the subtotals?

GRASP - Information Expert - Example Calculating the Sub Total GRASP - Information Expert 65 Sale time total() :Sale Which class has the 1 information needed for Contains calculating the subtotals? 1..* Sales LineItem quantity Described-by * 1 Product Description price Required information: quantity and price of each SalesLineItem quantity is available with SalesLineItem price is available with ProductDescription

GRASP - Information Expert - Example Calculating the Sub Total t = gettotal :Sale 1 *:st = getsubtotal lineitems[i]: SaleLinesItem GRASP - Information Expert Sale time total() 66 Which class has the information needed for calculating the subtotals? Sale SalesLineItem Design Class ProductDescription 1.1: p = getprice() Product Description knows sale total Responsibility knows line item subtotal knows product price Product Description price... getprice() SaleLinesItem quantity getsubtotal()

GRASP - Information Expert - Summary GRASP - Information Expert 67 Fulfillment of a responsibility often requires interaction amongst several objects (4 in our example) There are many semi-experts who collaborate in performing a task. Use of (Information) Expert guideline allows us to retain encapsulation of information Information hiding It often leads to lightweight classes collaborating to fulfill a responsibility

GRASP - Creator 68 Who should be responsible for creating an instance of a class?

GRASP - Creator 69 Who should be responsible for creating an instance of a class? Assign to class B the responsibility to create an object of class A if the following is true: B aggregates or (closely) uses objects of type A B records A B has the data to be passed to A when A is created B is an expert in the creation of A

GRASP - Creator GRASP - Creator 70 Sale time 1 Contains 1..* Sales LineItem quantity Described-by * 1 Product Description price Who should be responsible for creating a SalesLineItem?

GRASP - Creator GRASP - Creator 71 Sale time 1 Contains 1..* Sales LineItem quantity Described-by * 1 Product Description price Who should be responsible for creating a SalesLineItem? Sale contains SalesLineItem objects; hence, Sale is a good candidate for creating a SalesLineItem

GRASP - Creator GRASP - Creator 72 Communication Diagram Class Diagram makelineitem(quantity) :Sale Sale time 1: create(quantity) makelineitem(...) total() :SalesLineItem Communication diagram after assigning the responsibility for creating SalesLineItems to Sale.

GRASP - Creator GRASP - Creator 73 Variant A Register creates an instance of Payment and passes it to Sale. (Suggested by Creator as Register records Payments.) Variant B Sale creates an instance of Payment. (Suggested by Creator as Sale uses Payment. makepayment makepayment :Register 1: create(quantity) p:payment :Register 1: makepayment() :Sale 2: addpayment(p) :Sale 1.1: create() p:payment Which class should be responsible for creating a Payment?

GRASP - Creator GRASP - Creator 74 Variant A Register creates an instance of Payment and passes it to Sale. makepayment Sale creates an instance of Payment. makepayment Variant B :Register 1: create(quantity) p:payment :Register 1: makepayment() :Sale 2: addpayment(p) :Sale 1.1: create() p:payment Using this variant might lead to a non-cohesive class. If there are several system operations, and Register does some work related to each, it will be a large noncohesive class. This variant supports both: high cohesion and low coupling.

Example Designing makenewsale of the ProcessSale Use Case GRASP - Case Study 75...... Preconditions None System Operation Contract a Sale instance s was created Instance creation Postconditions s was associated with the Register Association formed the attributes of s are initialized

Example Designing makenewsale of the ProcessSale Use Case Creating a New Sale Object GRASP - Case Study 76 Who should be responsible for creating a new instance of some class? Creator

Example Designing makenewsale of the ProcessSale Use Case Creating a New Sale Object GRASP - Case Study 77 From the contract: a Sale instance was created. Creator suggests a class that... aggregates, contains or records the object (Sale) to be created. Sales LineItem quantity Contained-in Sale date time Paid-by 1..* 1 Payment amount 0..1 0..1 Records-sale-of 1 Captured-on Item * 1 Store address name 1 Register Stocked-in Houses

Example Designing makenewsale of the ProcessSale Use Case Creating a New Sale Object GRASP - Case Study 78 From the contract: a Sale instance was created. Creator suggests a class that... aggregates, contains or records the object (Sale) to be created. Sales LineItem quantity Contained-in Sale date time Paid-by 1..* 1 Payment amount 0..1 0..1 Records-sale-of 1 Captured-on Item * 1 Store address name 1 No Candidate Register Stocked-in Houses

Example Designing makenewsale of the ProcessSale Use Case Creating a New Sale Object GRASP - Case Study 79 From the contract: a Sale instance was created. Creator suggests a class that... aggregates, contains or records the object (Sale) to be created. Sales LineItem quantity Contained-in Sale date time Paid-by 1..* 1 Payment amount 0..1 0..1 Records-sale-of 1 Captured-on Item * 1 Store address name 1 No Candidate Register Stocked-in Houses

Example Designing makenewsale of the ProcessSale Use Case Creating a New Sale Object GRASP - Case Study 80 From the contract: a Sale instance was created. Creator suggests a class that... aggregates, contains or records the object (Sale) to be created. Sales LineItem quantity Contained-in Sale date time Paid-by 1..* 1 Payment amount 0..1 0..1 Records-sale-of 1 Captured-on Item * 1 Store address name 1 No Candidate Register Stocked-in Houses

Example Designing makenewsale of the ProcessSale Use Case GRASP - Case Study 81 From the contract:...the attributes of [the newly created Sale instance] are initialized. Since a Sale will also contain SalesLineItems it is necessary to further create a List object for storing the sale line items. :Register makenewsale create :Sale create lineitems : List<SalesLineItem> Interaction diagram showing the creation dependencies.

Design Heuristics J. Riel; Object-Oriented Design Heuristics; Addison- Wesley, 1996

Design Heuristics Design Heuristics 83 Design Heuristics help to answer the question: Is it good, bad, or somewhere in between? Object-Oriented Design Heuristics offer insights into object-oriented design improvement The following guidelines are language-independent and allow to rate the integrity of a software design Heuristics are not hard and fast rules; they are meant to serve as warning mechanisms which allows the flexibility of ignoring the heuristic as necessary Many heuristics are small tweakings on a design and are local in nature A single violation rarely causes major ramifications on the entire application.

Design Heuristics 84 Two areas where the object-oriented paradigm can drive design in dangerous directions......poorly distributed systems intelligence The God Class Problem...creation of too many classes for the size of the design problem Proliferation of Classes (Proliferation =dt. starke Vermehrung)

A Very Basic Heuristic Design Heuristics 85 All data in a base class should be private; do not use non-private data. Define protected accessor methods instead. If you violate this heuristic your design tends to be more fragile.

A Very Basic Heuristic Design Heuristics 86 All data in a base class should be private; do not use non-private data. Define protected accessor methods instead. public class Line { // a "very smart developer" decided: // p and v are package visible to enable efficient access /*package visible*/ Point p; } /*package visible*/ Vector v; public boolean intersects(line l) { } public boolean contains(point p) { } Implementation of a Line class as part of a math library. Line l1 = ; Line l2 = ; // check if both lines are parallel if (l1.v.equals(l2.v)) { } Some code in the same package that uses Line objects.

A Very Basic Heuristic Design Heuristics 87 All data in a base class should be private; do not use non-private data. Define protected accessor methods instead. public class Line { /*package visible*/ Point p1; /*package visible*/ Point p2; public boolean intersects(line l) { } public boolean contains(point p) { } } Now, assume the following change to the implementation of Line. The public interface remains stable - just implementation details are changed. Line l1 = ; Line l2 = ; // check if both lines are parallel if (l1.v.equals(l2.v)) { } The change breaks our code.

A Very Basic Heuristic Design Heuristics 88 All data in a base class should be private; do not use non-private data. Define protected accessor methods instead. public class Line { private Point p; private Vector v; public boolean intersects(line l) { } public boolean contains(point p) { } protected Vector getvector() { return v; }; } Better design. Line l1 = ; Line l2 = ; // check if both lines are parallel if (l1.getvector().equals(l2.getvector())) { } Some code in the same package that uses Line objects.

The God Class Problem The God Class Problem 89 Distribute system intelligence as uniformly as possible, that is, the top-level classes in a design should share the work uniformly. Beware of classes that have many accessor methods defined in their public interface. Having many implies that related data and behavior are not kept in one place. Beware of classes that have too much noncommunicating behavior, that is, methods that operate on a proper subset of the data members of a class. God classes often exhibit much noncommunicating behavior.

The Problem of Accessor Methods The God Class Problem - Behavioral Form 90 Point +getx() +setx(int) +gety() +sety(int) The class Point has accessor operations in the public interface. Are there any problems with this design of Point, you can think of? Is Point eventually giving too much implementation details away to clients?

The Problem of Accessor Methods The God Class Problem - Behavioral Form 91 Point +getx() +setx(int) +gety() +sety(int) The class Point has accessor operations in the public interface. Are there any problems with this design of Point, you can think of? Is Point eventually giving too much implementation details away to clients? The answer to this question is: No, accessor methods do not necessarily expose implementation details.

The Problem of Accessor Methods The God Class Problem - Behavioral Form 92 Point Accessor methods indicate poor encapsulation of related data and behavior; someone is getting the x- and y-values of Point objects to do something with them executing behavior that is related to points - that the class Point is not providing Often the client that is using accessor methods is a god class capturing centralized control that requires data from the mindless Point object +getx() +setx(int) +gety() +sety(int) But, still there is an issue. What is it?

The Problem of Accessor Methods The God Class Problem - Behavioral Form 93 public class Line { private Point p; private Vector v; public boolean intersects(line l) { } public boolean contains(point p) { } protected Vector getvector() {return v;}; public boolean isparallel(line l) { }; } Reconsider the Line class. Line l1 = ; Line l2 = ; // check if both lines are parallel if (l1.isparallel(l2)) { } Some code in the same package that uses Line objects.

Two Reasonable Explanations For the Need of Accessor Methods... The God Class Problem - Behavioral Form 94 a class performing the gets and sets is implementing a policy (policy = dt. Verfahren(-sweise)) or it is in the interface portion of a system consisting of an object-oriented model and a user interface

Implementing Policies Between Two or More Classes Example from the Course-scheduling Domain The God Class Problem - Behavioral Form 95 Student Course Captures static information about students, e.g., name, identification number, list of courses (s)he has taken, etc. Captures static information about the course objects, e.g., the course number, description, duration, minimum and maximum number of students, list of prerequisites, etc.

Implementing Policies Between Two or More Classes Example from the Course-scheduling Domain The God Class Problem - Behavioral Form 96 CourseOffering Student Captures static and dynamic information related to a particular section of a given course, e.g., the course being offered, the room and schedule, instructor, list of attendees, etc. Course

Implementing Policies Between Two or More Classes Example from the Course-scheduling Domain The God Class Problem - Behavioral Form 97 addstudent(s) :Course 2: checkprereq(c) :CourseOffering 1: c = getcourses() s:student First design for checking the prerequisites of students

Implementing Policies Between Two or More Classes Example from the Course-scheduling Domain The God Class Problem - Behavioral Form 98 addstudent(s) :Course 2: checkprereq(c) :CourseOffering 1: c = getcourses() s:student addstudent(s) :Course 1: p = getprereq() :CourseOffering 2: check(p) s:student Second design for checking the prerequisites of students

Implementing Policies Between Two or More Classes Example from the Course-scheduling Domain The God Class Problem - Behavioral Form 99 addstudent(s) :Course 2: checkprereq(c) :CourseOffering 1: c = getcourses() s:student addstudent(s) :Course 1: p = getprereq() :CourseOffering 2: check(p) s:student addstudent(s) :Course 1: p = getprereq() :CourseOffering 2: c = getcourses() s:student 3: check(p,c) The policy is implemented by course offering. Third design for checking the prerequisites of students

Implementing Policies Between Two or More Classes. Example from the Course-scheduling Domain The God Class Problem - Behavioral Form 100 addstudent(s) :Course 2: checkprereq(c) :CourseOffering 1: c = getcourses() s:student addstudent(s) :Course 1: p = getprereq() :CourseOffering 2: check(p) s:student addstudent(s) :Course 1: p = getprereq() :CourseOffering 2: c = getcourses() s:student 3: check(p,c) What do you think of these three designs? (Discuss the pros and cons - regarding the implementation of the policy - with your fellow students.)

The God Class Problem - Behavioral Form Summary The God Class Problem - Behavioral Form In general, always try to model the real world (Low representational gap facilitates maintenance and evolution.) But modeling the real world is not as important as the other heuristics. (E.g., in the real world a room does not exhibit any behavior, but for a heating system it is imaginable to assign the responsibility for heating up or cooling down a room to a corresponding class.) Basically, a god class is a class that does too much (Behavioral Form) By systematically applying the principles that we have studied previously, the creation of god classes becomes less likely 101

Classes That Model the Roles an Object Plays The Proliferation of Classes 102 Be sure that the abstractions that you model are classes and not simply the roles objects play.

Classes That Model the Roles an Object Plays The Proliferation of Classes 103 Variant A class Person { } class Father extends Person { } class Mother extends Person { } main () { Father f = new Father( ); Mother m = new Mother( ); } class Person { } Variant B main () { Person father = new Person( ); Person mother = new Person( ); } Whether to choose Variant A or B depends on the domain you are modeling; i.e. whether Mother and Father exhibit different behavior Before creating new classes, be sure the behavior is truly different and that you do not have a situation where each role is using a subset of Person functionality

Classes That Model the Roles an Object Plays The Proliferation of Classes 104 What do you think of the following design? Customer {abstract} MaleCustomer FemaleCustomer Which question do you have to ask yourself to decide if such a design makes sense?

Summary

Goal of the Lecture 106 The goal of this lecture is to enable you to systematically carry out small(er) software projects that produce quality software. Always assign responsibilities to classes such that the coupling is as low as possible, the cohesion is as high as possible and the representational gap is as minimal as possible. Coupling and cohesion are evaluative principles to help you judge OO designs. Design heuristics are not hard rules, but help you to identify weaknesses in your code to become aware of potential (future) issues.

Goal of the Lecture 107 The goal of this lecture is to enable you to systematically carry out small(er) commercial or open-source projects. Software Project Management Project Start Project End Start of an Iteration Requirements Management Domain Modeling Modeling Testing Coding