grasp patterns presented by dr. shazzad hosain. patterns a pattern describes a problem and solution,...

41
GRASP Patterns Presented By Dr. Shazzad Hosain

Upload: angelica-fletcher

Post on 27-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

GRASP Patterns

Presented ByDr. Shazzad Hosain

Page 2: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

PatternsA pattern describes a problem and solution,

and given a name.Examples are Singleton, Adapter, Factory etc.

A pattern ExampleName: Information ExpertContext/Problem: What is a basic principle by

which to assign responsibilities to objects?Solution: Assign a responsibility to the class that

has the information needed to fulfill it.

Page 3: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Repeating PatternsThe very term Pattern means a repeating

thing.The point of pattern is not to express new

design ideasInstead patterns codify existing tried-and-true

knowledge, idioms, and principles: the more honed and widely use, the better.

Page 4: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Naming Patterns Improves CommunicationEngineers can discuss among themselves a

complex principle or design idea with a simple name.

Fred: “Where do you think we should place the responsibility for creating a SalesLineItem? I think a Factory.”

Wilma: “By Creator, I think Sale will be suitable.”

Fred: “Oh, right – I agree”.

Page 5: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

GRASP PatternsQuestion: What is GRASP patters?Answer: They describe fundamental principles

of object design and responsibility assignment, expressed as patterns.

GRASP stands for General Responsibility Assignment Software Patterns. Information ExpertCreatorHigh CohesionLow CouplingController

Page 6: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

1. Information Expert (or Expert)Context/Problem: What is a basic principle by

which to assign responsibilities to objects?Solution: Assign a responsibility to the class that

has the information needed to fulfill it.Example: In NextGen POS application, some class

needs to know the grand total of a sale.Start by asking “Who should be responsible for

knowing the grand total of a sale?”By Information Expert we should look for a class

that has the information needed to determine the total.

Where should we look, domain or design model?First look into design model, if not then look into

domain model

Page 7: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Domain Model vs. Design Model

Let’s assume we are starting from domain model

Page 8: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

NextGen POSSystem Domain Model

Who has the information to determine the sales total?

Page 9: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Add ResponsibilitiesSo we add a software class into design model similarly

called Sale, and give the responsibility of knowing its total, expressed with the method named getTotal ().

A responsibility is not the same thing as a method, but methods are implemented to fulfill responsibilities.

Responsibilities are implemented using methods that either act alone or collaborate with other methods and objects

Page 10: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Types of ResponsibilityTwo types of responsibilities, knowing and doing.Knowing responsibilities of an object include:

Knowing about private encapsulated dataKnowing about related objectsKnowing about things it can derive or calculateE.g. Sale object is responsible for knowing its total.

Doing responsibilities of an object include:Doing something itself e.g. creating object or doing a

calculationInitiating action in other objectsControlling and coordinating activities in other objectsE.g. a Sale is responsible for creating SalesLineItems” (a

doing)

Page 11: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Associations of Sale

Page 12: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Determining Sales TotalDetermining sales total needs

SalesLineItem.quantity and ProductSpecification.price.

By Information Expert SalesLineItem should determine the subtotal.

Thus Sale should send getSubtotal messages to each of SalesLineItems and sum the results.

Page 13: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Determining Sales TotalProductSpecification is an information

expert on answering its price;Therefore, a message must be sent to

it asking for its price.

Page 14: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Class ProductSpecification

String desription;

float price ;

int itemID

void setItemID (int itemID) {

this.itemID = itemID ;

}

int getItemID () {

return this.itemID ;

}

void setPrice (float price)

float getPrice ()

void setDescription (String desc)

String getDescription ()

End Class

Class SalesLineItem

ProductSpecification ps ;

int quantity ;

void setProductSpecification (…)

Pro..Spec.. getProductSpecification ()

void setQuantity (int qty)

int getPrice ()

void setDescription (String desc)

String getDescription ()

float getSubtotal (){

return quantity * ps.getPrice ()

}

End Class

Implementation Classes

Page 15: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Class Sale

LinkedList <SalesLineitem> sliList;

Date date ;

Time time ;

float getTotal (){

float total = 0 ;

for each item in sliList

total = total + item.getSubTotal ()

end For

return total ;

}

End Class

Class SalesLineItem

ProductSpecification ps ;

int quantity ;

void setProductSpecification (…)

Pro..Spec.. getProductSpecification ()

void setQuantity (int qty)

int getPrice ()

void setDescription (String desc)

String getDescription ()

float getSubtotal (){

return quantity * ps.getPrice ()

}

End Class

Page 16: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

ContradictionsSometimes a solutions suggested by Information

Expert is undesirable, usually because of problems in coupling and cohesion.

Who should be responsible for saving a Sale in a database?

Certainly Sale object contains much of the information so Sale object is the natural choice.

But then Sale class mush have codes related to SQL, JDBC etc.

Related PatternsLow CouplingHigh Cohesion

Page 17: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

GRASP PatternsInformation ExpertCreatorLow CouplingHigh CohesionController

Page 18: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

2. CreatorContext/Problem: Who should be responsible

for creating a new instance of some class?Solution: Assign class B the responsibility to

create a class A, if:B aggregates A objectsB contains A B records instances of AB closely uses AB has the initializing data that will be passed to A

when it is createdExample: In NextGen POS application, who

should be responsible for creating a SalesLineItem instance?

Page 19: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Creating a SalesLineItem

Page 20: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Finding Creator ClassSometimes a creator is found by looking for the

class that has the initializing data that will be passed in during creation.

Example: A Payment instance needs to be initialized, when created, with the Sale total.A Payment object will create Sale object orA Sale object will create Payment object

Since Sale knows the total, Sale is a candidate creator for Payment

Page 21: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

ContradictionsOften creation requires significant complexity

such as conditional creation based on external property, using recycled instances for performance reason etc.

Delegate creation to a helper class called a Factory rather than suggested by Creator.

Related PatternsLow couplingFactory

Page 22: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

GRASP PatternsInformation ExpertCreatorLow CouplingHigh CohesionController

Page 23: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

3. Low CouplingContext/Problem: How to support low dependency,

low change of cost and increased reuse?Solution: Assign a responsibility so that coupling

remains lowCoupling is a measure of how strongly one element

is connected to, has knowledge of, or relies on other elements.Low coupling means not dependent on too many

elements e.g. classes, subsystems etc.High Coupling has the following problem

Changes in related classes force local changesHarder to understand in isolationHarder to reuse because its use requires other classes on

which it is dependent.

Page 24: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Low Coupling ExampleConsider the following partial class diagram form POS

study

Assume we need to create a Payment instance and associate with Sale.

What Class should be responsible for this?Creator pattern suggests Register as a candidate

because Register “records” a Payment.UML notation

Register class is coupled with Payment classDesign 1

Page 25: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Low Coupling ExampleAlternatively create Payment and associate

with the Sale class

Which design is best?In any case Sale must eventually be coupled to

knowledge of a Payment. So design 2 is better.

Page 26: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

SuggestionsIn practice, the level of coupling alone can't be

considered in isolation from other principles such as Information Expert and High Cohesion. Nevertheless, it is one factor to consider in improving design.

There is no absolute measure of when coupling is too high. It depends on developer’s design skill.

Even extremely low coupling is not desirable.OO systems means “a system of connected objects

that communicate via messages.”Extreme low/zero coupling means single object with lot of

responsibilities that is in-cohesive, bloated and complex.Moderate degree of coupling is normal and necessary

in OOA/D

Page 27: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

ContradictionsHigh coupling to stable elements and to

pervasive elements is seldom a problem.For example, J2EE application can safely couple

to the Java libraries, because they are stable and widespread.

Pick your battlesIt is not high coupling per se that is the problem;

it is high coupling to elements that are unstable in some dimension such as their interface, implementation, or mere presence.

Page 28: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Pick the BattlesPick the battles between lowering coupling and

encapsulating things.Focus on points of realistic high instability or evolutionExample: In NextGen project, different third-party tax

calculators (with unique interface) need to be connected to the system.Therefore designing for Low Coupling at this point is

practical.Benefits

Not affected by change in other componentsSimple to understand in isolationConvenient to reuse.

Related pattersProtected Variation

Page 29: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

GRASP PatternsInformation ExpertCreatorLow CouplingHigh CohesionController

Page 30: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

4. High CohesionContext/Problem: How to keep complexity

manageable?Solution: Assign a responsibility so that cohesion

remains high.Cohesion: In object design cohesion is a measure

of how strongly related and focused the responsibilities or an element are.Object with high cohesion does not do a

tremendous amount of work.Low cohesion does many unrelated things.

Page 31: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

High Cohesion Example

In this case probably its ok because there are only three classes.

But if there are fifty system operations, all received by Register, then it would become bloated in-cohesive object.

Page 32: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

High Cohesion Example

This Register class is highly cohesive.

Page 33: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Cohesion and Coupling, Yin and Yang

Bad cohesion usually begets bad coupling, and vice versa

They have inter-dependant influence, thus the term “yin and yang of software engineering”.

Example: consider a GUI widget class that represents and paints a widget, saves data to a database, and invokes remote object services.It is not only profoundly in-cohesive, but it is

coupled to many disparate elements.

Page 34: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

GRASP PatternsInformation ExpertCreatorLow CouplingHigh CohesionController

Page 35: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

5. ControllerContext/Problem: Who should be responsible

for handling an input system event?Solution: Assign system handling

responsibility to a class if:Represents the overall system, device or sub-

system (façade controller)Represents a use case scenario within which the

system event occurs, often named <UseCaseName>Handler, <UseCaseName>Coordinator, <UseCaseName>Sesssion

Page 36: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Controller

Example

Page 37: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Choice of ControllersA controller is a non-user interface object

responsible for receiving or handling a system event.First category of controller is a façade controller

representing the overall system, device or a subsystem.Suitable when there are not too-many system events.

Second category is a use-case controller, when there should be many controllers

Façade Controller

Use-case Controller

Page 38: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Allocation of System OperationsFaçade

Controller

Use-case Controllers

Page 39: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Desirable Coupling between Interface Layer and Domain Layer

Page 40: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

Less Desirable Coupling between Interface Layer and Domain Layer

Page 41: GRASP Patterns Presented By Dr. Shazzad Hosain. Patterns A pattern describes a problem and solution, and given a name. Examples are Singleton, Adapter,

ReferencesChapter 16 of “Applying UML and Patterns – An

Introduction to Object-Oriented Analysis and Design and the Unified Process” – by Craig Larman

Chapter 17 – 20 self study.