chapter 7: object design examples with grasp. objective design use case realizations. apply grasp to...
TRANSCRIPT
Chapter 7:Chapter 7: Object Design Examples Object Design Examples with GRASP with GRASP
ObjectiveObjective
Design use case realizations.Design use case realizations.
Apply GRASP to assign responsibilities to Apply GRASP to assign responsibilities to classes.classes.
Apply UML to illustrate and think through Apply UML to illustrate and think through the design of objects.the design of objects.
7.1. What is a Use Case 7.1. What is a Use Case Realization?Realization?
A use-case realization A use-case realization – Describes how a particular use case is realizeDescribes how a particular use case is realize
d within the Design Model, in terms of collabord within the Design Model, in terms of collaborating objects.ating objects.
the connection between the requirements expressthe connection between the requirements expressed as use cases and the object design that satisfieed as use cases and the object design that satisfies the requirements. s the requirements.
Operation: enterItem(…)
Post-conditions:- . . .
Operation Contracts
Sale
date. . .
SalesLineItem
quantity
1..*1 . . .
. . .
Domain Model
Use-Case Model
Design Model: Register
enterItem(itemID, quantity)
: ProductCatalog
d = getProductDescription(itemID)
addLineItem( d, quantity )
: Sale
Require-ments
Business Modeling
Design
Sample UP Artifact Relationships
: System
enterItem(id, quantity)
Use Case Text
System Sequence Diagrams
makeNewSale()
system events
Cashier
Process Sale
: Cashier
use case
names
system operations
Use Case Diagram
SupplementarySpecification
Glossary
starting events to design for, and detailed post-condition to satisfy
Process Sale
1. Customer arrives ...2. ...3. Cashier enters item identifier.
inspiration for names of some software domain objects
functional requirements that must be realized by the objects
ideas for the post-conditions
Register
...
makeNewSale()enterItem(...)...
ProductCatalog
...
getProductDescription(...)...
1*
non-functional requirements
domain rules
item details, formats, validation
7.1. What is a Use Case 7.1. What is a Use Case Realization?Realization?
:RegisterenterItem
:RegisterendSale
:RegistermakePayment
1: ???
1: ???
1: ???
:RegistermakeNewSale 1: ???
makeNewSale, etc., are the system operations from the SSD
each major interaction diagram starts with a system operation going into a domain layer controller object, such as Register
DOMAIN LAYERUI LAYER
Window objects or
GUI widget objectsor
Web control objects
. . .
7.2. Artifact Comments7.2. Artifact Comments
SSDs, System Operations, Interaction DiaSSDs, System Operations, Interaction Diagrams, and Use Case Realizations grams, and Use Case Realizations
: Register
: Sale
makeNewSalecreate
: Register
enterItem(...)
: ProductCatalog
desc = getProductDesc( itemID )
. . .
UI LAYER
Window objects or
GUI widget objectsor
Web control objects
. . .
DOMAIN LAYER
7.2. Artifact Comments7.2. Artifact Comments
The Domain Model and Use Case The Domain Model and Use Case RealizationsRealizations– The Domain Model inspires some of the The Domain Model inspires some of the
software objects, software objects, such as a Sale conceptual class and Sale software such as a Sale conceptual class and Sale software class class
1: makeLineItem(...)enterItem(id, qty)
1.1: create(...)
:Register :Sale
:SalesLineItem
7.3. What's Next?7.3. What's Next?
The remainder of this chapter is organized The remainder of this chapter is organized as follows:as follows:– A relatively detailed discussion of the design oA relatively detailed discussion of the design o
f the NextGen POS.f the NextGen POS.– Likewise, for the Monopoly case study,Likewise, for the Monopoly case study,
Applying UML and patterns to these case studies. let's get into the details…
7.4. Use Case Realizations for the 7.4. Use Case Realizations for the NextGen IterationNextGen Iteration
– Who should be responsible for calculating the Sale totWho should be responsible for calculating the Sale total? al?
By Expert, it should be the Sale itself, implemented as a getTBy Expert, it should be the Sale itself, implemented as a getTotal method.otal method.
– Who should be responsible for calculating the SalesLiWho should be responsible for calculating the SalesLineItem subtotal? neItem subtotal?
By Expert, it should be the SalesLineItem itself, implemented By Expert, it should be the SalesLineItem itself, implemented as a getSubtotal method.as a getSubtotal method.
– Who should be responsible for providing the ProductDWho should be responsible for providing the ProductDescription price? escription price?
By Expert, it should be the ProductDescription itself, implemeBy Expert, it should be the ProductDescription itself, implemented as a getPrice operation.nted as a getPrice operation.
My goodness, that was detailed!
7.4. Use Case Realizations for the 7.4. Use Case Realizations for the NextGen IterationNextGen Iteration
The Sale.getTotal Design The Sale.getTotal Design
:Saletot = getTotal 1 * [i = 1..n]: st = getSubtotal
:ProductDescription
1.1: pr = getPrice
lineItems[ i ]: SalesLineItem
by Expert by ExpertUML: note the selector notation to select elements from the lineItems collection
7.4. Use Case Realizations for the 7.4. Use Case Realizations for the NextGen IterationNextGen Iteration
:Saletot = getTotal 1 *[ i = 1..n]: st = getSubtotal
:ProductDescription
1.1: pr = getPrice
lineItems[ i ] :SalesLineItem
«method»public void getTotal(){ int tot = 0; for each SalesLineItem, sli tot = tot + sli.getSubtotal(); return tot}
7.4. Use Case Realizations for the 7.4. Use Case Realizations for the NextGen IterationNextGen Iteration
How to Design How to Design makePaymentmakePayment? ? – Two Candidates for Creating the Payment Two Candidates for Creating the Payment
Register Register – By CreatorBy Creator
“ “register" records account information in real domainregister" records account information in real domain– By ExpertBy Expert
Register is the controller that receives the system opRegister is the controller that receives the system operation makePayment message.eration makePayment message.
SaleSale– It will closely use a Payment It will closely use a Payment
7.4. Use Case Realizations for the 7.4. Use Case Realizations for the NextGen IterationNextGen Iteration
1: makePayment(cashTendered)
1.1: create(cashTendered)
:Register :Sale
:Payment
makePayment(cashTendered)
by Controller by Creator and Low Coupling
When there are alternative design choices When there are alternative design choices – take a closer look at the cohesion and coupling take a closer look at the cohesion and coupling
implications of the alternativesimplications of the alternatives – and possibly at the future evolution pressures and possibly at the future evolution pressures
on the alternativeson the alternatives
7.4. Use Case Realizations for the 7.4. Use Case Realizations for the NextGen IterationNextGen Iteration
Logging a Sale Logging a Sale – Who is responsible for knowing all the logged Who is responsible for knowing all the logged
sales and doing the logging?sales and doing the logging?Store Store
– the logged sales are strongly related to its financethe logged sales are strongly related to its finance
SalesLedger SalesLedger – makes sense as the design grows and the Store becomemakes sense as the design grows and the Store become
s incohesive s incohesive – SalesLedger is not in domain modelSalesLedger is not in domain model
7.4. Use Case Realizations for the 7.4. Use Case Realizations for the NextGen IterationNextGen Iteration
Store
...
addSale(s : Sale)...
SalesLedger
...
addSale(s : Sale)...
Store is responsible for knowing and adding completed Sales.
Acceptable in early development cycles if the Store has few responsibilities.
SalesLedger is responsible for knowing and adding completed Sales.
Suitable when the design grows and the Store becomes uncohesive.
Sale
...
...
Sale
...
...
Logs-completed Logs-completed
* *
1 1
7.4. Use Case Realizations for the 7.4. Use Case Realizations for the NextGen IterationNextGen Iteration
1: makePayment(cashTendered)
1.1: create(cashTendered)
:Register s :Sale
:Payment
makePayment(cashTendered)
:Store
2: addSale(s)
completedSales: List<Sale>
2.1: add(s)
by Expert
note that the Sale instance is named's' so that it can be referenced as a parameter in messages 2 and 2.1
7.4. Use Case Realizations for the 7.4. Use Case Realizations for the NextGen IterationNextGen Iteration
Calculating the Balance Calculating the Balance – Who is responsible for knowing the balance?Who is responsible for knowing the balance?
need the sale total and payment cash tenderedneed the sale total and payment cash tendered
s :Sale pmt: Payment1: amt = getAmountbal = getBalance
2: t = getTotal
{ bal = pmt.amount - s.total }
7.4. Use Case Realizations for the 7.4. Use Case Realizations for the NextGen IterationNextGen Iteration
The Final NextGen DCD for Iteration-1 The Final NextGen DCD for Iteration-1
SalesLineItem
quantity : Integer
getSubtotal()
ProductCatalog
...
getProductDesc(...)
ProductDescription
description : Textprice : MoneyitemID: ItemID
...
Store
address : Addressname : Text
addCompleteSale(...)
Payment
amount : Money
...
1..*
1..*
Register
...
endSale()enterItem(...)makeNewSale()makePayment(...)
Sale
isComplete : Booleantime : DateTime
becomeComplete()makeLineItem(...)makePayment(...)getTotal()
1
1
1
1
1
1
*
catalog
catalog
register
currentSale
descriptions{Map}
lineItems{ordered}
payment
completedSales{ordered}
description
7.4. Use Case Realizations for the 7.4. Use Case Realizations for the NextGen IterationNextGen Iteration
How to Connect the UI Layer to the DomaiHow to Connect the UI Layer to the Domain Layer? n Layer? – An initializer object called from the application An initializer object called from the application
starting method (e.g., the Java main method) starting method (e.g., the Java main method) creates both a UI and a domain object and pacreates both a UI and a domain object and passes the domain object to the UI.sses the domain object to the UI.
– A UI object retrieves the domain object from a A UI object retrieves the domain object from a well-known source, such as a factory object thwell-known source, such as a factory object that is responsible for creating domain objects.at is responsible for creating domain objects.
7.4. Use Case Realizations for the 7.4. Use Case Realizations for the NextGen IterationNextGen Iteration
7.4. Use Case Realizations for the 7.4. Use Case Realizations for the NextGen IterationNextGen Iteration
How to show the running total in UIHow to show the running total in UI– Add a getTotal method to the Register. Add a getTotal method to the Register.
Lower coupling from the UI to the domain layer Lower coupling from the UI to the domain layer
make Register less cohesive.make Register less cohesive.
– A UI directly sends messages to the Sale. A UI directly sends messages to the Sale. increases the coupling from the UI to the domain laincreases the coupling from the UI to the domain layer. yer.
7.4. Use Case Realizations for the 7.4. Use Case Realizations for the NextGen IterationNextGen Iteration
7.4. Use Case Realizations for the 7.4. Use Case Realizations for the NextGen IterationNextGen Iteration
Initialization and the 'Start Up' Use Case Initialization and the 'Start Up' Use Case – When to Create the Initialization Design?When to Create the Initialization Design?
Do the initialization design last.Do the initialization design last.
– How do Applications Start Up? How do Applications Start Up? create an initial domain object or a set of peer create an initial domain object or a set of peer initial domain objects initial domain objects
– in the starting main method or in a Factory object called in the starting main method or in a Factory object called from the main method from the main method
the initial domain object is responsible for the the initial domain object is responsible for the creation of its direct child domain objects. creation of its direct child domain objects.
7.4. Use Case Realizations for the 7.4. Use Case Realizations for the NextGen IterationNextGen Iteration
public class Main { public class Main {
public static void main( String[] args ) { public static void main( String[] args ) {
// Store is the initial domain object. // Store is the initial domain object. // The Store creates some other domain object// The Store creates some other domain object
s. s.
Store store = new Store(); Store store = new Store(); Register register = store.getRegister();Register register = store.getRegister();ProcessSaleJFrame frame = new ProcessSaleJFrame frame = new
ProcessSaleJFrame( register );ProcessSaleJFrame( register ); ... ...
}}} }
7.4. Use Case Realizations for the 7.4. Use Case Realizations for the NextGen IterationNextGen Iteration
Choosing the Initial Domain Object Choosing the Initial Domain Object – a class at or near the root of the containment a class at or near the root of the containment
or aggregation hierarchy of domain objects. or aggregation hierarchy of domain objects. Store.create DesignStore.create Design– Create a Store, Register, ProductCatalog, and Create a Store, Register, ProductCatalog, and
ProductDescriptions.ProductDescriptions.– Associate the ProductCatalog with ProductDeAssociate the ProductCatalog with ProductDe
scriptions.scriptions.– Associate Store with ProductCatalog.Associate Store with ProductCatalog.– Associate Store with Register.Associate Store with Register.– Associate Register with ProductCatalogAssociate Register with ProductCatalog
7.4. Use Case Realizations for the NextGen 7.4. Use Case Realizations for the NextGen IterationIteration
:Store :Register
pc:ProductCatalog
create 2: create(pc)
1: create
1.2: loadProdSpecs()
descriptions:Map<ProductDescription>
1.1: create
1.2.2*: put(id, pd)
1.2.1*: create(id, price, description)
pd:ProductDescriptionthe * in sequence number indicates the
message occurs in a repeating section
pass a reference to the ProductCatalog to the Register, so that it has permanent visibility to it
by Creatorcreate an empty collection object
Multiplicity between classes of objects in the Domain Model and Design Model may not be the same.
7.5. Use Case Realizations for the 7.5. Use Case Realizations for the Monopoly IterationMonopoly Iteration
7.5. Use Case Realizations for the 7.5. Use Case Realizations for the Monopoly IterationMonopoly Iteration
How to Design playGame? How to Design playGame? – Choosing the Controller Class Choosing the Controller Class
MonopolyGame / MGame MonopolyGame / MGame
PlayMonopolyGameHandlerPlayMonopolyGameHandler
PlayMonopolyGameSessionPlayMonopolyGameSession
7.5. Use Case Realizations for the 7.5. Use Case Realizations for the Monopoly IterationMonopoly Iteration
The Game-Loop AlgorithmThe Game-Loop Algorithm– turn a player rolling the dice and moving the pieceturn a player rolling the dice and moving the piece
– round all the players taking one turnround all the players taking one turn
Now the game loop:Now the game loop:
for N rounds for N rounds
for each Player p for each Player p
p takes a turn p takes a turn
Who is Responsible for Controlling the Game Who is Responsible for Controlling the Game Loop?Loop?
7.5. Use Case Realizations for the 7.5. Use Case Realizations for the Monopoly IterationMonopoly IterationInformation NeededInformation Needed Who Has the InformationWho Has the Information
the current round countthe current round count No object has it yet, but assigning thiNo object has it yet, but assigning this to the MonopolyGame object is justs to the MonopolyGame object is justifiable.ifiable.
all the playersall the players MonopolyGame is a good candidate.MonopolyGame is a good candidate.
7.5. Use Case Realizations for the 7.5. Use Case Realizations for the Monopoly IterationMonopoly Iteration
playRound helper methodplayRound helper method– Factors the play-single-round logic into a helpFactors the play-single-round logic into a help
er method; er method; it is good to organize cohesive chunks of behavior iit is good to organize cohesive chunks of behavior into small separate methods.nto small separate methods.
– Good OO method design encourages small mGood OO method design encourages small methods with a single purpose. ethods with a single purpose.
This supports High Cohesion at the method level.This supports High Cohesion at the method level.
7.5. Use Case Realizations for the 7.5. Use Case Realizations for the Monopoly IterationMonopoly Iteration
Who Takes a Turn? Who Takes a Turn? – Rolling the dice Rolling the dice – Moving a piece to the square indicated by the Moving a piece to the square indicated by the
total of the dice face values. total of the dice face values.
a naive reaction might be to say "a Player object should take the turn"
7.5. Use Case Realizations for the 7.5. Use Case Realizations for the Monopoly IterationMonopoly Iteration
Information NeededInformation Needed Who Has the InformationWho Has the Information
current location of the current location of the playerplayer
a Piece knows its Square and a a Piece knows its Square and a PlayerPlayer knows its Piece. knows its Piece.
the two Die objectsthe two Die objects MonopolyGameMonopolyGame is a candidate sin is a candidate since we think of the dice as being pace we think of the dice as being part of the game.rt of the game.
all the squares all the squares BoardBoard is a good candidate. is a good candidate.
Interesting Problem! Interesting Problem! – There are three partial information experts for the "take a turn" There are three partial information experts for the "take a turn"
responsibilityresponsibility
7.5. Use Case Realizations for the 7.5. Use Case Realizations for the Monopoly IterationMonopoly Iteration
When there are multiple partial information expertsWhen there are multiple partial information experts – place the responsibility in the dominant oneplace the responsibility in the dominant one
the object with the majority of the information the object with the majority of the information
When there are alternative design choices,When there are alternative design choices,– consider the coupling and cohesion impact of consider the coupling and cohesion impact of
each, and choose the best. each, and choose the best.
When there is no clear winnerWhen there is no clear winner– consider probable future evolution of the consider probable future evolution of the
software objects and the impact software objects and the impact in terms of Information Expert, cohesion, and in terms of Information Expert, cohesion, and coupling. coupling.
7.5. Use Case Realizations for the 7.5. Use Case Realizations for the Monopoly IterationMonopoly Iteration
7.5. Use Case Realizations for the 7.5. Use Case Realizations for the Monopoly IterationMonopoly Iteration
Taking a Turn Taking a Turn – calculating a random number total between 2 and calculating a random number total between 2 and
12 (the range of two dice)12 (the range of two dice)Die Die
– calculating the new square locationcalculating the new square locationBoard Board
– moving the player's piece from an old location to a moving the player's piece from an old location to a new square locationnew square location
Piece Piece
Who Coordinates All This? Who Coordinates All This? – Player Player The Problem of Visibility The Problem of Visibility
– Player need visibility to the Die, Board, and Piece Player need visibility to the Die, Board, and Piece objects objects
7.5. Use Case Realizations for the 7.5. Use Case Realizations for the Monopoly IterationMonopoly Iteration
7.5. Use Case Realizations for the 7.5. Use Case Realizations for the Monopoly IterationMonopoly Iteration
// style #1; used in the official solution // style #1; used in the official solution
public void roll() { public void roll() {
faceValue = // random num generation faceValue = // random num generation
} }
public int getFaceValue() { public int getFaceValue() {
return faceValue; return faceValue;
} }
// style #2; why is this poor? // style #2; why is this poor?
public int roll() {public int roll() {
faceValue = // random num generation faceValue = // random num generation
return faceValue; return faceValue;
} }
7.5. Use Case Realizations for the 7.5. Use Case Realizations for the Monopoly IterationMonopoly Iteration
Command-Query Separation Principle Command-Query Separation Principle – a command method that performs an action ofa command method that performs an action of
ten has side effects such as changing the statten has side effects such as changing the state of objects, and is voide of objects, and is void
– a query that returns data to the caller and has a query that returns data to the caller and has no side effectsno side effects
7.5. Use Case Realizations for the 7.5. Use Case Realizations for the Monopoly IterationMonopoly Iteration
Initialization and the 'Start Up' Use Case Initialization and the 'Start Up' Use Case
Questions & AnswersQuestions & Answers