Вы находитесь на странице: 1из 281

Object-Oriented Analysis and

Rectangle 8

Design
with Patterns, Process, and the UML

Introduction
Introduction

 Welcome!
 Introductions
– Course leader: Dr. Trần Vũ Bình
– Participants:
 MSc. Nguyễn Ngọc Tú (Lecturer)
 MSc. Phạm Thị Thu Trang (Lecturer)
 Hồ Thuỵ Hương Thuỷ (Tutor)
 Nguyễn Bá Trung (Tutor)
 Prerequisites: Object-Oriented Programming
 Logistics
Overview and Objectives
 Learn how to “think in objects”
 Requirements and analysis of the problem
domain
 Design of a solution
– Assign responsibilities to objects
– Design patterns
– Architectural issues
– Java and/or C++ issues
 Unified Process
 UML
 Practice!
Assessment components

Hoa Sen University 4


Team work

 Software development is a team-oriented


activity…
 Two assignments will work around the
same project
 You need to work in the same team for
both assignments
 Preferred team size: 2-3 students
 You can do it by yourself
 Form your team as early as possible
Hoa Sen University 5
Team Project – Collaborative
Tagging System
 Your client:
– Charities Inc. a search engine company
 Your goal:
– Design a system to allow users to upload and
collaboratively tag web contents: article or
image.
 Manage registered users
 Manage contents and their tags
 Produce summaries upon request

Hoa Sen University 6


Project Task

 Assignment 1
– Prepare requirement document
– Write use cases
– Develop Domain Model
 Assignment 2
– Write Design Document
– Implement the system (desktop version)
– System Demo

Hoa Sen University 7


Software

 Microsoft Visio
– Licensed software
– Installed on the lab PC

Hoa Sen University 8


Rectangle 8

What is OOAD?

Lecture 1

Hoa Sen University 9


Today’s lecture topic

 What’s OOAD?
 Functional decomposition and its problem
 What’s UML?
 Software Development Process

Hoa Sen University 10


What is Analysis and Design

 Analysis emphasizes an investigation of


the problem and requirements rather
than how a solution is defined
 Design emphasizes a conceptual
solution that system fulfils the
requirements rather than its
implementation

Hoa Sen University 11


What is O-O A&D?

 The essence of O-O A&D is to consider a


problem domain and logical solution from
the perspective of objects (things,
concepts, or entities)
 O-O Analysis emphasizes finding and
describing the objects – or concepts- in
the problem domain
 O-O Design emphasizes defining logical
software objects (things, concepts, or
entities) that have attributes and methods

Hoa Sen University 12


Object vs. Function Oriented Analysis

Library
Information
System

OOA&D Structured A&D


Decompose by objects and concepts Decompose by functions and processes

Catalogue Librarian

Book Library

Hoa Sen University 13


Functional Decomposition

 A very simple development case


– You are asked to write code to access a list of
shapes that were stored in a database then
display them
 What steps we need to achieve this?
1.Locate the list of shapes in the database
2.Open up the list of shapes
3.Sort the list according to some order
4.Display the individual shapes on the monitor

Hoa Sen University 14


Functional Decomposition

 We might breakdown some step further


– Identify the type of shapes
– Get the location of the shape
– Call the appropriate function that will display
the shape, giving it the shape’s location
 This is called functional decomposition
because the analyst breaks down
(decomposes) the problem into the
functional steps that compose it.

Hoa Sen University 15


How do people do things

 Case:
– You are an instructor at a seminar. People in
your seminar have another class to attend
following yours, but don’t know where it is
located. One of your responsibilities is to
make sure everyone knows how to get to the
next class.

Hoa Sen University 16


A “software like” option
 Steps:  Procedures needed:
– Get list of people in the class – A way of getting the list of
– For each person on this list, people in the class
do the following: – A way of getting the schedule
 Find the next class he or she for each person in the class
is taking – A program that gives
 Find the location of that class someone directions from
 Find the way to get from your your classroom to any other
classroom to the persona’s classroom
next class
– A control program that works
 Tell the person how to get to
for each person in the class
his or her next class
and does the required steps
for each person

Hoa Sen University 17


A “human like” option

 What’s the alternatives?


– Post a directions to go from this classroom to
the other classrooms and tell everyone in the
class
“ I have posted the locations of the other classes
following this in the back of the room, as well as
the locations of the other classrooms. Please use
them to go to your next classroom. ”
– Assume everyone knows what his or her next
class is

Hoa Sen University 18


Difference?

 Option 1: giving explicit directions to


everyone – pay attention to lots of details.
You are responsible for everything
 Option 2: giving general instructions and then
expect each person will figure out how to do
the task individually
– Two kinds of objects
 Instructor: responsible for posting the instruction
 Students: knowing their own next classes, able to follow
the instruction
 Key point: Shift of responsibility!

Hoa Sen University 19


Dealing with changing
requirements
 Impact
– What if you need to distinguish postgraduate
students from undergraduate students?
– Option 1: change the control program a lot
– Option 2: add an additional routine for
graduate students to follow
 The second case can minimize changes

Hoa Sen University 20


Dealing with changing
requirements
 What makes it happen?
– The people are responsible for their own
behaviour
– The control program can talk to different types
of people as if they were exactly the same
– The control program does not need to know
about any special steps that students might
need to take when moving from class to class

Hoa Sen University 21


Key Steps in OOAD [1]

 Use Case: a textual description or “story”


describing the system
 Play a Dice Game: Player requests to roll
the dice. System presents results: If the
dice face value totals seven, player wins;
otherwise, player loses.

Hoa Sen University 22


Key steps in OOAD [2]

 a domain model that shows the noteworthy


domain concepts or objects, attributes, and
associations
Player Die
1 Rolls  2
name faceValue
1 2
Plays
1

DiceGame
1 Includes 

Hoa Sen University 23


Key steps in OOAD [3]

 Interaction Diagram: shows the flow of


messages between software objects (method
invocation)
:DiceGame die1 : Die die2 : Die

play()
roll()

fv1 := getFaceValue()

roll()

fv2 := getFaceValue()

Hoa Sen University 24


Key steps in OOAD [4]

 Class Model: shows attributes, methods and


associations for software (solution) objects (not
domain objects!)

DiceGame Die

die1 : Die 1 2 faceValue : int
die2 : Die
getFaceValue() : int
play() roll()
Hoa Sen University 25
Iterative and Evolutionary
Development
 Iterative development
– Development is organized into a series of
short, fixed-length mini-projects called
iterations.
– the outcome of each is a tested, integrated,
and executable partial system.
– Known as iterative and incremental
development

Hoa Sen University 26


Iterative and evolutionary
development
Requirements  Requirements  Feedback from 
iteration N leads to 
Design Design refinement and 
Time adaptation of the 
Implementation & Implementation & requirements and 
Test & Integration  Test & Integration  design in iteration 
& More Design & More Design N+1.
Final Integration  Final Integration 
& System Test & System Test

3 weeks (for example)
Iterations are fixed in  The system grows 
length, or timeboxed. incrementally.

Hoa Sen University 27


Handle change on iterative project
Early iterations are farther from the "true 
path" of the system. Via feedback and  In late iterations, a significant change in 
adaptation, the system converges towards  requirements is rare, but can occur. Such 
the most appropriate requirements and  late changes may give an organization a 
design.  competitive business advantage.  

one iteration of design, 
implement, integrate, and test

Hoa Sen University 28


How long should an iteration be?

 Most iterative methods recommend an


iteration length between two and six weeks.
 Iteration are timeboxed, or fixed in length
 Date slippage is illegal
 If it seems difficult to meet the deadline, the
recommended response is to de-scope –
remove tasks or requirements from the
iteration, and include them in a future
iteration

Hoa Sen University 29


How to do Iterative and Evolutionary
Analysis and Design?
1 2 3 4 5 ... 20

requirements workshops

Imagine this will 
ultimately be a 20­
iteration project.

requirements

requirements
software

software
In evolutionary iterative 
development, the 
requirements evolve 
over a set of the early 
iterations, through a 
series of requirements 
90% 90%
workshops (for 
example). Perhaps 
after four iterations and 
50%
workshops, 90% of the 
requirements are  30%
defined and refined.  20% 20%
5% 8% 10%
Nevertheless, only  2%
10% of the software is 
Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5
built.
a 3­week iteration

week 1 week 2 week 3


M T W Th F M T W Th F M T W Th F

kickoff meeting  team agile  start  de­scope  final check­in  demo and  next 


clarifying iteration  modeling &  coding &  iteration  and code­ 2­day  iteration 
goals with the team.  design,  testing goals if  freeze for the  requirements  planning 
1 hour UML  too much  iteration  workshop meeting;
whiteboard  work baseline 2 hours
sketching.
5 hours Most OOA/D and 
Use­case modeling 
applying UML during 
during the workshop
this period

Hoa Sen University 30


Agile Methods and attitudes

 Agile development methods usually


apply timeboxed iterative and evolutionary
development, employ adaptive planning,
promote incremental delivery and include
other values and practices that encourage
agility – rapid, and flexible response to
change.
 Example
– programming in pairs
– test-driven development
Hoa Sen University 31
Agile Modelling

 Adopting an agile method does not mean


avoiding any modelling
 The purpose of modelling and models is
primarily to support understanding and
communication, not documentation
 Don’t model or apply the UML to all or
most of the software design
 Use the simplest tool possible

Hoa Sen University 32


Agile modelling (cont)

 Don’t model alone


 Create models in parallel
 Use “good enough” simple notation while
sketching with a pen on paper
 Know that all models will be inaccurate
 Developers themselves should do the OO
design modelling, for themselves, not to
create diagrams that are given to other
programmers to implement.
Hoa Sen University 33
Layers and textbook case study

minor focus
User Interface
explore how to connect to 
other layers

primary focus 
of case studies
application  Sale Payment
logic layer explore how to 
design objects

other layers or  secondary 
Logging ... Database Access ...
components focus

Hoa Sen University 34


Case study strategy

Iteration 1

Iteration 2
Introduces just those 
analysis and design  Iteration 3
skills related to  Additional analysis and 
iteration one. design skills introduced.
Likewise.

Hoa Sen University 35


Cases
 Case one: The NextGen POS
system
– A POS system is a computerized
application used (in part) to record
sales and handle payments
– Hardware: computer, bar code
scanner
– Software
– Interfaces to service applications:
tax calculator, inventory control
 Case Two: The Monopoly Game
System

Hoa Sen University 36


Rectangle 8

Inception

Lecture 2

Hoa Sen University 37


Agenda

 Recap
 Inception overview
 Evolutionary Requirements
 Use cases
 Other requirements
 Assignment 1 instruction

Hoa Sen University 38


What we learned last week

 Difference between analysis and design


 Different focuses of functional
decomposition and object-oriented
approach
 Benefit of OO approach
 UML
 Iterative development
 Agile modelling

Hoa Sen University 39


Inception Questions

 What is the vision and the business case


for this project?
 Feasible?
 Buy and/or build?
 Rough estimate of cost: $10K, $100K,
$1M,
…
 Should we proceed or stop?

Hoa Sen University 40


Goals of Inception

 “…to do just enough investigation to form


a rational, justifiable opinion of the overall
purpose and feasibility of the potential new
system.”
 Envision the product scope, vision and
business case
 Do the stakeholders have basic
agreement on the vision of the project? Is
it worth investigating seriously?

Hoa Sen University 41


Artefacts in Inception
Artefacts Comments

Vision and Business Describe the high-level goals and constraints, the business case, and
Case provides an executive summary
Use-Case Model Describes the functional requirements. During inception, the names of
most use cases will be identified, and perhaps 10% of the use cases will
be analysed in detail
Supplementary Other requirements
specification
Glossary Key domain terminology, and data dictionary

Risk List & Risk Describes the risks (business, technical, resource, schedule) and ideas for
Management plan their mitigation or response
Prototypes and proof-of- To clarify the vision, and validate technical ideas
concepts
Iteration Plan Describes what to do in the first elaboration iteration

Phase Plan & Software Low-precision guess for elaboration phase duration and effort. Tools,
Development plan people, education, and other resources
Development Case A description of the customized UP steps and artefacts for this project.

Hoa Sen University 42


It is not an inception if

 It takes more than a few weeks


 You attempt to define most requirements
 Estimates are expected to be reliable
 You define a concrete architecture
 No business case or vision document
 Too little or too much use case modelling

Hoa Sen University 43


Hoa Sen University 44
Understanding Requirements

 “Capabilities and conditions to which the


system and project must conform”
[Jacobson et al., 1999]
 Challenges: {find, communicate, record,
manage} the requirements
 Requirements always change, so
effective management is critical

Hoa Sen University 45


Evolutionary vs. Waterfall
requirements
 UP embraces change in requirements as
a fundamental driver on projects
 Start production-quality programming and
testing long before most of the
requirements have been analysed or
specified.

Hoa Sen University 46


The FURPS+ Model

 Functional – features, capabilities, security


 Usability – human factors, help,
documentation
 Reliability – failure frequency, recoverability
 Performance – response times, throughput,
accuracy, availability, resource utilization
 Supportability – adaptability, maintainability,
internationalization, configurability

Hoa Sen University 47


The FURPS+ Model

 Implementation – resource limitations,


languages/tools, hardware
 Interface – with legacy systems
 Operations – sysop management
 Packaging – delivery, installation
 Legal – licensing, etc.

Use FURPS+ as a global checklist when identifying


requirements for a system you are designing

Hoa Sen University 48


Other Terminology

 Quality Attributes, or “-ilities”


– Usability, reliability, supportability,
performance (non-functional)
 Functional vs. Non-Functional
– Behavioural features vs. everything else
 The quality attributes have a strong
influence on the architecture of a system

Hoa Sen University 49


Document Requirements

 Primarily, in the use case model


– functional requirements
 Also, Supplementary Specifications
– other requirements
 Glossary – noteworthy terms
 Vision – high-level requirements
 Business Rules – Requirements or policies
that transcend one software project – many
applications in the same domain may need to
conform to them

Hoa Sen University 50


The Use Case Model

 “Writing Requirements in Context”


 Identify user goals, corresponding system
functions / business processes
 Brief, casual, and “fully-dressed” formats
 Iterative refinement of use cases

Hoa Sen University 51


Stories

 Using a system to meet goals


 E.g. brief format
– Process Sale: A customer arrives at a checkout with items to
purchase. The cashier uses the POS system to record each
purchased item. The system presents a running total and line-
item details. The customer enters payment information, which
the system validates and records. The system updates inventory.
The customer receives a Receipt from the system and then
leaves with the items.

Usually, writing the stories is more important than


diagramming a use case model in UML

Hoa Sen University 52


Definitions

 Actor: something with a behaviour;


person, system, organization
 Scenario: specific sequence of actions
and interactions between actor(s) and
system (= one story; success or failure)
 Use Case: collection of related success
and failure scenarios describing the actors
attempts to support a specific goal

Hoa Sen University 53


Examples

 Handle Returns
– Main Success Scenario: A customer arrives at a
checkout with items to return. The cashier uses
the POS system to record each returned item…
– Alternate Scenarios:
 If they paid by credit, and the reimbursement
transaction to their credit account is rejected, inform the
customer and pay them with cash.
 If the item identifier is not found in the system, notify the
cashier and suggest manual entry of the identifier code
 If the system detects failure to communicate with the
external accounting system… (etc.)

Hoa Sen University 54


Why use cases?

 A key attitude in use case work is to focus


on the question ‘How can using the
system provide observable value to the
user, or fulfil their goals? rather than
merely thinking of requirements in terms
of a list of features or functions
 Focus on business process, not
technology features

Hoa Sen University 55


Common use case formats

 Brief: one-paragraph summary, main


success scenario
– When? During early requirements analysis
 Casual: multiple, informal paragraphs
covering many scenarios
– When? Also early requirements analysis
 Fully-Dressed: all steps and variations
written in detail with supporting sections
– See
http://alistair.cockburn.us/usecases/usecases.html
– When? Before each elaboration starts, do it for a portion of
use cases selected for the following elaboration

Hoa Sen University 56


NextGen POS example
 A fully dressed example
– Use case name
– Scope & level
– Primary Actor
– Stakeholders and Interests
– Preconditions
– Success Guarantee
– Main Success scenario
– Extensions
– Special Requirements
– Technology and Data Variations List
– Miscellaneous
Hoa Sen University 57
Details ...
 Use case name
– Start with a verb
– “Process Sale”
 Scope
– The system under design
– “NextGen POS application”
 Level
– User-goal or subfunction
– “User-goal”
 Primary actor
– Calls on the system to delivery the service
– “Cashier”
 Stakeholders and Interests
– Who care about this use case and what do they want?
– “Government Tax Agencies: Want to collect tax from every sale”

Hoa Sen University 58


Details…

 Preconditions
– What must be true on start, and worth telling
the reader
– “Cashier is identified and authenticated”
 Success Guarantee
– What must be true on successful completions,
and worth telling the reader
– “Sales is saved. Tax is correctly calculated…”

Hoa Sen University 59


Details…
 Main Success Scenario (or Basic flow)
– A typical, unconditional happy path scenario of
success
– Record steps:
 An interaction between actors
 A validation (usually by the system)
 A state change by the system
– E.g.
1.Customer arrives at a POS checkout
2.Cashiers starts a new sale
3.Cashier enters item identifier
4.System record sales line item…
– Cashier repeats steps 3-4 until indicates done.
1.System presents total with taxes calculated

Hoa Sen University 60


Details…
 Extensions ( or Alternate Flows )
– Alternate scenarios of success or failure
 Scenario branches (success/failure)
 Longer/more complex than basic flow
 Branches indicated by letter following basic flow step number, e.g. “3a”
 Two parts: condition, handling
– E.g.
 Extensions:
 3a. Invalid identifier
1. System signals error and reject entry
– When possible write the condition as something that can be detected
 5a: System can not communication with external tax calculation system
 5a: External tax calculation system not working
– If condition can arise within a range of steps
 3-6a: customer asks Cashier to remove an item from the purchase
1. Cashier enters the item identifier for removal from the sale
2. System displays updated running total.
– At the end of extension handling, by default the scenario merges back
with the main success scenario, unless the extension indicates
otherwise

Hoa Sen University 61


Details…

 Special Requirements
– Related non-functional requirements
 Touch screen UI on a large flat panel monitor
 Language internationalization on the text displayed
 Technology and Data Variation List
– Varying I/O methods and data formats (non-
functional constraints expressed by the
stakeholder)
 Item identifier entered by laser scanner or keyboard
 Credit account information entered by card reader or
keyboard

Hoa Sen University 62


Guidelines 1

 Write in an essential UI-Free Style


– The narrative is expressed at the level of the
user’s intentions and system’s responsibilities
– Essential Style
1. Administrator identified self.
2. System authenticates identity.
3. …
 Concrete Style
– Administrator enters ID and passwd in dialog box
– System authenticates Administrator.
– System displays the “edit users” window

Hoa Sen University 63


Guideline 2

 Write Black-Box use cases


– Focus on “what”, not “how”
– Good: The system records the sale
– Bad: The system writes the sale to a
database
– Worse: The system generates a SQL INSERT
statement…

Hoa Sen University 64


Guideline 3

 Take an actor and actor-goal perspective


– “a set of use-case instances, where each
instance is a sequence of actions a system
performs that yields an observable result of
value to a particular actor”
 Write requirements focusing on the users or actors
of a system.
 Focus on understanding what the actor considers
a valuable result.

Hoa Sen University 65


How to find use cases (Guideline 4)

 Choose the system boundary


– Software, hardware, person, organization
 Identify the primary actors
– Goals fulfilled by using the system
 Identify goals for each actor
 Define use cases that satisfy goals
– User-goal level use cases will be one-to-one with user
goals
– Exception: CRUD (Create, Retrieve, Update, Delete)
 E.g., “edit user”, “delete user”, …
 Collapse into a single use case (e.g., Manage Users)
Hoa Sen University 66
Choose the system boundary

 In the case study, the POS system itself is


the system under design;
 Everything outside of it is outside the
system boundary
 Identify what is outside would help to
identify the boundary

Hoa Sen University 67


Find primary actor and goals
 Questions to help find Actor Goals
actors and goals Cashier Process sales
– Is “time” an actor because Process rentals
the system does something Handle returns
in response to a time event?
– In addition to human primary Manager Start up
actors, are there any external Shut down
software or robotic systems
that call upon services of the System Admin Add user
system? Modify user
– …
Sales Analyse sales and
activity performance data
System

Hoa Sen University 68


Actors, Goals & Boundaries

Enterprise Selling Things

Checkout Service
Sales Tax
Agency
POS System
Goal: Collect 
taxes on sales Sales Activity
System Cashier

Customer

Goal: Buy items Goal: Analyze sales  Goal: Process sales


and performance data

Hoa Sen University 69


Valid or useful use cases

 Which of these is a valid use case?


– Negotiate a Supplier Contract
– Handle Returns
– Log In
– Move Piece on Game Board
 All are valid, but at different level; better
question is “what is a useful level to
express use cases”

Hoa Sen University 70


Guideline 5: Tests

 What tests can help find useful use


cases?
– Boss Test
 Log in does not sounds like something that will make your
boss happy
– The EBP Test
 Elementary Business Process
– “A task performed by one person in one place at one time, in response
to a business event, which adds measurable business value and leaves
the data in a consistent states, e.g. Approved Credit or Price Order.
– The size test
 A use case is very seldom a single action or step.

Hoa Sen University 71


Guideline 5 : Tests (cont’ed)

 Applying the tests


– Negotiate a Supplier Contract
 Much broader and longer than an EBP
– Handle returns
 Ok with the boss. Seems like an EBP. Size is good
– Log In
 Not OK with the boss, no measurable business value
– Move Piece on Game Board
 Single step – fail the size test

 Reasonable violations of the tests


– It is sometimes useful to write separate subfunction-level use
cases representing subtasks or steps within a regular EBP-level
use case.

Hoa Sen University 72


Applying UML: Use Case Diagram
system boundary NextGen POS communication

Process Sale alternate
notation for 
Customer a computer 
Payment system actor
Authorization
Service
Handle Returns
«actor»
actor Tax Calculator
Cashier

«actor» Use case diagram is an


Cash In Accounting
System Excellent picture of the
Manager system context. It serves
«actor»
«actor» Analyze Activity
HR System as a communication tool
Sales Activity
System  that summarizes the
Manage Security behaviour of a system and
its actors
System Manage Users
Administrator use case
. . .

Hoa Sen University 73


Diagram notation
For a use case context  Show computer system actors 
diagram, limit the use cases to  with an alternate notation to 
user­goal level use cases. human actors.

NextGen

«actor»
Process Sale Payment
Authorization
Service
Cashier
. . .

primary actors on  supporting actors 
the left on the right

Hoa Sen University 74


Alternate actor notation

NextGen Some UML alternatives to 
illustrate external actors that 
Process Sale «actor» are other computer systems.
Payment
«system» Authorization The class box style can be 
Payment Payment Service used for any actor, computer or 
Authorization Authorization human. Using it for computer 
...
Service Service actors provides visual 
distinction.

Hoa Sen University 75


The include relationship

 Partial behaviour that is common across several


use cases
– E.g., PayByCredit occurs in several use cases:
Process Sale, Process Rental, and so on
 Solution: represent as a separate use case
– “Refactoring and linking text to avoid duplication”
(Larman)
 “Use include when you are repeating yourself in
two or more separate use cases and you want to
avoid repetition” (Fowler)

Hoa Sen University 76


Example of include relationship

 UC1: Process Sale


–…
– Main Success Scenario:
1. Customer arrives at a POS checkout with goods and/or services to purchase.

7. Customer pays and System handles payment

– Extensions:
7b. Paying by credit: Include Handle Credit Payment.
7c. Paying by check: Include Handle Check Payment

 UC7: Process Rental


–…
– Extensions:
6b. Paying by credit: Handle Credit Payment

Hoa Sen University 77


Included use case
 UC12: Handle Credit Payment
– …
– Level: sub-function
– Main Success Scenario
1. Customer enters their credit account information
2. System sends payment authorization request to an external
payment authorization service system and request payment
approval

– Extensions:
 2a. System detects failure to collaborate with external system:
– 1. system signals error to cashier
– 2. Cashier asks customer for alternate payment

Hoa Sen University 78


The include relationship
 To decompose an overwhelmingly long use case into
subunits to improve comprehension
 Using include with asynchronous event handling
 Eg.
– UC8: Process self-help check out
– …
– Main Success Scenario
– 1…
– Extensions:
 a* At any time, customer selects printing help: Present Printing Help

Hoa Sen University 79


Model include relationship in use case
diagram
NextGen POS

Process Sale

Cashier
«include» «include» «actor»
Accounting
«include» System

Handle Check Handle Cash Handle Credit


Payment Payment Payment
Customer «actor»
«include» Credit
«include» «include» Authorization
Service
UML notation: 
the base use 
Process Rental
case points to 
the included use 
case

Handle Returns

Manage Users

...

Hoa Sen University 80


The extend relationship

 How to add an extension to a use case


that is frozen or too complicated?
 Solution: use extend to relate to an
addition use case
 Describe where and under what condition
the additional use case extends the
behaviour of the base use case (use
extension point)

Hoa Sen University 81


Example of extend relationship

 UC1: Process Sale (the base use case)


– …
– Extension Points: VIP Customer, step1. Payment, step 7.
– Main Success Scenario:
1. Customer arrives at a POS checkout with goods and/or services to purchase

7. Customer pays and system handles payment

 UC15: Handle Gift Certificate Payment (the extending use case)
– ...
– Trigger: Customer wants to pay with gift certificate
– Extension Points: Payment in Process Sale
– Level: subfunction
– Main Success Scenario:
1. Customer gives gift certificate to Cashier
2. Cashier enters gift certificate ID

Hoa Sen University 82


Extend relationship in use case
diagram

Process Sale

Extension Points:
Payment UML notation: 
VIP Customer 1. The extending use case 
points to the base use case.
«extend»
Payment, if Customer  2. The condition and 
presents a gift certificate extension point can be 
shown on the line.
Handle Gift Certificate 
Payment

Hoa Sen University 83


Extend vs. include relationships

 Direction of the relationship


– For include relationship, the event triggering the target
use case is described in the flow of event of the
source use case (user-goal level)
– For extend relationships, the event triggering the
source (the extending) use case is described in the
source use case( sub-function level). The base use
case have no knowledge of the extending use case
 The purpose of adding include and extend
relationships is to reduce or remove
redundancies from the use case model

Hoa Sen University 84


Rectangle 8

Domain Model

Lecture 3

Hoa Sen University 85


Agenda

 Recap
 Case Requirements
 Elaboration process
 Domain model
– Introduction and definition
– How to create a domain model

Hoa Sen University 86


Recap

 Inception activities
 Different types of requirements
 Scenario & Use case
 Writing Use Cases
 Use Case Diagram
 Use case relationships

Hoa Sen University 87


Case requirements

 The requirements for the first iteration of


the NextGen POS:
– Implement a basic, key scenario of the
Process Sale use case
– Implement a Start Up use case as necessary
to support the initialization needs of the
iteration
– Nothing fancy or complex is handled
– No collaboration with external services
– No complex pricing rules are applied
Hoa Sen University 88
Case requirements

 Monopoly
– Implement a basic, key scenario of the Play
Monopoly Game use case: players moving
around the squares of the board
– Implement a start Up use case as necessary
to support the initialization needs of the
iteration
– Two to eight players can play
– A game is played as a series of rounds

Hoa Sen University 89


Case requirements

 Monopoly (cont)
– Play the game for only 20 rounds
– After the dice are rolled, the name of the player and
the roll are displayed. When the player moves and
lands on a square, the name of the player and the
name of the square that the player landed on are
displayed.
– In iteration-1 there is no money, no winner or loser, no
properties to buy or rent to pay, and no special
squares of any kind
– Square name will be “Go”, “Square 1”, “Square
2”,…“Square 39”
Hoa Sen University 90
Incremental Development

 Incremental development for the same


use case across iteration
A use case or feature is 
1 2 3 . . . often too complex to 
complete in one short 
iteration. 

Therefore, different parts 
Use Case Use Case Use Case or scenarios must be 
Process Sale Process Sale Process Sale allocated to different 
iterations.

Use Case
Process Rentals
Feature: 
Logging

Hoa Sen University 91


Process: inception
 What happened in inception
– Last only one week
– Most actors, goals and use cases named
– Most use cases written in brief format; 10-20% of the use cases are
written in fully dressed detail
– Recommendations on what components to buy/build/reuse, to be
refined in elaboration
 Technical proof-of-concept prototypes and other
investigations to explore the technical feasibility of
special requirements/
 High-level candidate architecture and components
proposed – NOT necessary to be final or correct
 Plan for the first iteration

Hoa Sen University 92


Process: on to Elaboration

 What happens in Elaboration


– The core, risky software architecture is programmed
and tested
– The majority of requirements are discovered and
stabilized
– The major risks are mitigated or retired
– Commonly, 2 or more timeboxed iterations
 Elaboration in one sentence
– Build the core architecture, resolve the high-risk
elements, define most requirements, and estimate
the overall schedule and resources.

Hoa Sen University 93


Process: on to Elaboration

 Best practices in elaboration


– Do short timeboxed risk-driven iterations
– Start programming early
– Adaptively design, implement, and test the
core and risky parts of the architecture
– Test early, often, realistically
– Write most of the use cases and other
requirements in detail, through a series of
workshops, once per elaboration iteration

Hoa Sen University 94


Domain models

 Illustrates noteworthy concepts in a


domain
 Drawn with UML class diagram
 As with all things in an agile modelling and
UP spirit, a domain model is optional
 Input
– Problem Description, Use Cases, …
 Output
– A set of class diagrams
Hoa Sen University 95
Example
concept Sales
Item
or domain  LineItem Records­sale­of 
object 1
quantity 0..1

1..* *
Stocked­in
association Contained­in

1 1

Sale Store

attributes date  address


time 0..1 name
1
1
Houses
Paid­by 1..*

1 Register
Captured­on 
Payment
1
amount

Identifying a rich set of conceptual classes is at the heart of OO analysis


Hoa Sen University 96
What is a domain model

 A domain model is a visual representation of


conceptual classes or real-situation objects in a
domain.
– Various names
 conceptual models, domain object models, analysis object
models
 A domain model is illustrated with a set of
CLASS DIAGRAMS in which no operations
(method signatures) are defined

Hoa Sen University 97


Domain models is a visual dictionary

 Domain model provides a conceptual


perspective
– Domain objects or conceptual classes
– Associations between conceptual classes
– Attributes of conceptual classes
 The information it illustrates could
alternatively have been expressed in plain
text

Hoa Sen University 98


Domain model is not a picture of
software objects

 Domain model is
visualization of a real­world concept in 

a visualization of Sale

dateTime
the domain of interest

it is a not a picture of a software class

things in a real-
world domain of
interest av
o id
SalesDatabase
software artifact; not part 
of domain model

 Not suitable in a
domain model av
o id
date
Sale
software class; not part 
of domain model
time
– Software artefacts print()

– Responsibilities or
methods
Hoa Sen University 99
What are conceptual classes

 A conceptual class may be


considered in terms of date
Sale concept's symbol

time
– Symbol – words or images
representing a conceptual
"A  sale  represents  the  event 
class of  a  purchase  transaction.  It 
has a date and time." 
concept's intension

– Intension – the definition of


a conceptual class
sale­1

– Extension – the set of sale­3


sale­2 concept's extension

examples to which the sale­4

conceptual class applies

Hoa Sen University 100


Domain model vs. Data model

 Data model – persistent data to be stored


somewhere
 Domain model also include
– Temporary object
– Object with no attribute

Hoa Sen University 101


Motivation
 Help to understand the key concepts in a business or problem
domain
 Lower representational gap with OO Modelling
UP Domain Model
Stakeholder's view of the noteworthy concepts in the domain.

Sale
A Payment in the Domain Model  Payment 1
1 Pays­for
is a concept, but a Payment in  date
the Design Model is a software  amount
time
class. They are not the same 
thing, but the former inspired the 
inspires 
naming and definition of the 
objects 
latter.
and 
names in
This reduces the representational 
gap.
Sale
This is one of the big ideas in  Payment
object technology. 1 1 date: Date
Pays­for
amount: Money startTime: Time

getBalance(): Money getTotal(): Money
. . .

UP Design Model
The object­oriented developer has taken inspiration from the real world domain 
in creating software classes. 

Therefore, the representational gap between how stakeholders conceive the 
domain, and its representation in software, has been lowered.

Hoa Sen University 102


How to create a Domain Model

 Steps
– Find the conceptual classes
– Draw them as classes in a UML class diagram
– Add associations and attributes

Hoa Sen University 103


Find conceptual classes

 Three strategies to find conceptual


classes
– Reuse or modify existing models
 There are published, well-crafted domain models
and data models for common domains: inventory,
finance, health..
 Books: Analysis patterns by Martin Fowler, Data
Model Patterns by David Hay, Data Model
Resource Book by Len Silverston
– Use a category list
– Identify noun phrases
Hoa Sen University 104
Use a category list

 Use a conceptual class category list:


– Physical or tangible objects
Register, Airplane
– Specifications, descriptions of things
ProductSpecification, FlightDescription
– Places
Store, Airport
– Transactions
Sale, Payment, Reservation
– etc. (see Table 9.1 for a fuller list)
Hoa Sen University 105
Noun Phrase Identification

 Noun Phrase Identification [Abbot 83]


– Analyse textual description of the domain
 Identify nouns and noun phrases (indicate
candidate classes or attributes)
 Caveats:
– Automatic mapping isn’t possible
– Textual descriptions are ambiguous! (different
words may refer to the same class)

Hoa Sen University 106


Example: flow of event

 The customer enters a store with the intention of


buying a toy for his 3 years old child Alice.
 Help must be available within less than one
minute.
 The store owner gives advice to the customer.
The advice depends on the age range of the
child and the attributes of the toy.
 The customer selects a dangerous toy which is
kind of unsuitable for the child.
 The store owner recommends a soft doll.

Hoa Sen University 107


Mapping parts of speech to object
model components

Part of speech Model component Examples


Proper noun Instance Alice
Common noun Class Customer, toy
Doing verb Operation Buy, recommend
Being verb Inheritance Is a kind of, is one
of
Having verb Aggregation Has, consists of,
(Composition) includes
Modal verb Constraints Must be
Adjective attributes Attributes 3 years old

Hoa Sen University 108


Example: find and draw conceptual
classes

 Case study: POS Domain


– Input
 fully dressed use case model (excellent textual
description of the domain)
 Iteration-1: success (cash-only) scenario of
Process Sale use case.
– Strategy: category list
– There is no such thing as a “correct” list. It is a
somewhat ARBITRARY collection of domain
vocabulary that the modellers consider
noteworthy
Hoa Sen University 109
Initial POS domain model

Register Item Store Sale

Sales
Cashier Customer Ledger
LineItem

Cash Product Product


Payment Catalog Description

Hoa Sen University 110


Initial Domain model of Monopoly
game simulation

Hoa Sen University 111


Agile modelling style

 It is normal to miss significant conceptual


classes during early domain modeling and
to discover them later during DESIGN
sketching or PROGRAMMING.
 We can maintain the model by drawing it
with tool
 OFTEN, a long-life OO analysis domain
model does not add value

Hoa Sen University 112


Include report objects?

 Receipt is a noteworthy term in POS domain


 It has duplicate information contained in sale
and payment.
 Guidelines
– In general, showing a report of other information in a
domain model is not useful
– However, it might has special role in terms of
business rules. We might have a reason to show it in
the model.

Hoa Sen University 113


Class or Attributes

 Class or attribute?
– If we do not think of some conceptual class X
as a number or text in the real world, X is
probably a conceptual class, not an attributes

Hoa Sen University 114


Description Class
 What’s the rationale for representing the description or
specification separately from the item
 In the following domain model, can you tell the difference
between (description, price, itemID) and serial number?
Item

description Worse
price
serial number
itemID

ProductDescription
Item
description Describes Better
price 1 * serial number
itemID

Hoa Sen University 115


Description classes
 When are description classes
useful? Flight
Airport
– There needs to be a description date Flies­to Worse

about an item or service, number


time * 1 name

independent of the current


existence of any examples of
those items or services
– Deleting instances of things Flight
FlightDescription Better
they describe results in a loss date
Described­by

of information that needs to be time * 1 number

maintained, but was incorrectly *


associated with the deleted Describes­flights­to
1
things
Airport
– It reduces redundant or
name
duplicated information

Hoa Sen University 116


Associations
 Definition
– An association is a relationship between objects that indicates
some meaningful and interesting connection
– UML def.: associations are defined as “the semantic relationship
between two or more classifiers that involve connections among
their instances.”

association

Records­current
Register Sale
1 1

Hoa Sen University 117


When to show association

 Associations for which knowledge of the


relationship needs to be preserved for some
duration
– In the POS domain
 We need to remember what SalesLineItem instances are associated with a
Sale.
 Cashier may look up ProductionDescription during the process of sale, but
we do not need to remember who looked up what after the sales has been
made.
– In the monopoly domain
 We need to remember what Square a Piece is on.
 Dice total may indicate a Piece how many steps to move on, what Square it
will land, but we do not need to remember that

 We should avoid showing too many associations

Hoa Sen University 118


Associations and implementation

 There is no direct relationship between


associations and implementation.
 Associations do not indicate a certain
implementation construct.
 Many associations may be implemented in
software differently

Hoa Sen University 119


Association Notation

­"reading direction arrow"
­it has no meaning except to indicate direction of 
 reading the association label
­often excluded

Register Records­current  Sale


1 0..1

association name multiplicity

Hoa Sen University 120


Naming association

 Name an association based on a


ClassName-VerbPhrase-ClassName
format
 Eg.
– Sales paid-by CashPayment
 Bad alternative: Sales uses CashPayment
– Piece is-on Square
 Bad alternative: Piece has Square

Hoa Sen University 121


Applying UML: multiplicity
 Multiplicity defines how many instances of a class A can
be associated with one instance of class B

Store Stocks Item


1
*

multiplicity of the role

Hoa Sen University 122


Multiplicity values
 Multiplicity focus on the * T
zero or more; 
"many"
relationship at a particular
moment, rather than over a
1..*
span of time. T one or more

 Eg. “In countries with


monogamy laws, a person 1..40
T one to 40
can be Married-to only one
other person at any
particular moment, even 5
T exactly 5
though over a span of time,
that same person may be
3, 5, 8
married to many persons.” T exactly 3, 5, or 8

Hoa Sen University 123


Multiplicity values

Store Stocks  Item


1
or 0..1
*

Multiplicity should "1" or "0..1"?

The answer depends on our interest in using the model. Typically and practically, the muliplicity communicates a 
domain constraint that we care about being able to check in software, if this relationship was implemented or 
reflected in software objects or a database.  For example, a particular item may become sold or discarded, and thus 
no longer stocked in the store. From this viewpoint, "0..1" is logical, but ...

Do we care about that viewpoint? If this relationship was implemented in software, we would probably want to ensure 
that an Item software instance would always be related to 1 particular Store instance, otherwise it indicates a fault or 
corruption in the software elements or data.

This partial domain model does not represent software objects, but the multiplicities record constraints whose 
practical value is usually related to our interest in building software or databases (that reflect our real­world domain) 
with validity checks. From this viewpoint, "1" may be the desired value.  

Hoa Sen University 124


Multiple association between two
classes

* Flies­to 1
Flight Airport
Flies­from
* 1

Hoa Sen University 125


Find association

 Use the common associations list


– A is a physical part of B
 Square – Board
– A is a logical part of B
 SalesLineItem – Sale
– A uses or submanages B
 Cashier- Register
– A communicates with B
 Customer – Cashier
– etc.
Hoa Sen University 126
POS partial domain model
Records­sale­of 

Product
Ledger Product Description
Catalog Contains
1 1..*
1 1
1
0..1 Records­
Used­by Describes
accounts­
Sales for * *
LineItem Store
Item
Stocks
1 1
* 1..*
1..*
1
Contained­in Logs­ Houses
1 completed 1..*

Sale * Register
Captured­on
0..1 1

1 1 Is­for 1
Paid­by  Works­on
1 1 1

CashPayment Customer Cashier

Hoa Sen University 127


Monopoly partial domain model

Hoa Sen University 128


Attributes

 An attribute is a logical data value of an


object
 When to show attribute
– Include attributes that the requirements
suggest or imply a need to remember
information
– Eg.
 Sale needs a dateTime attribute
 Store needs a name and address.

Hoa Sen University 129


UML notation
 Attributes are shown in the second compartment of the
class box.
 Type and other information may optionally be shown
 Derived attribute
– The total attribute in the Sale can be calculated from other
information
– It is worth noting down.

Sale Math Person

­ dateTime : Date + pi : Real = 3.14 {readOnly} firstName


­ / total : Money middleName : [0..1]
lastName

Private visibility  Public visibility readonly 
attributes attribute with initialization Optional value

Hoa Sen University 130


Suitable attribute types

 Most attribute
Cashier

types should be Worse


name
currentRegister
not a "data type" attribute

what are often


Cashier Register
thought of as Better
name
1 Uses 1
number

“primitive” data
types Flight destination is a complex 
Worse concept

 Relate conceptual destination

classes with an Better Flight 1 Flies­to 1 Airport

association, not
with an attribute
Hoa Sen University 131
Data types as attributes
 We sometimes represent what may initially be considered a number
or string as a new data type class in the domain model
 We can show the data type only in attribute compartment or as a
separate class associated with another class.

ItemID Address

Product 1 1 1 1 street1
OK id Store
Description street2
manufacturerCode
countryCode cityName
...

Product Store
Description
OK address : Address
itemId : ItemID

Hoa Sen University 132


Attributes are NOT foreign keys

 During implementation, there are many ways to relate objects,


including foreign key, but the decision should be deferred till
DESIGN stage.

Cashier
Worse a "simple" attribute, but being 
name used as a foreign key to relate to 
currentRegisterNumber another object

Cashier Register
Better 1 Works­on 1
name number

Hoa Sen University 133


Modelling quantities

Payment
not useful
amount : Number

Payment Quantity Unit


Has­amount Is­in
* 1
amount : Number * 1
...

Payment quantities are pure data 
values, so are suitable to 
amount : Quantity better
show in attribute section

Payment variation: Money is a 
specialized Quantity whose 
amount : Money unit is a currency

Hoa Sen University 134


Iterative and evolutionary domain
model

 Is the domain model correct?


– There is no such thing as a single correct
domain model!
– Domain model is incrementally evolve over
several iterations.
– In each iteration, the domain model is limited
to the prior and current scenarios under
consideration.

Hoa Sen University 135


Contracts and
Rectangle 8

UML interaction diagrams

Lecture 4

Hoa Sen University 136


Agenda

 System sequence diagram


 Operation Contract
 On to Object design
– Interaction diagrams
 Sequence diagrams
 Communication diagrams

Hoa Sen University 137


System Sequence Diagram
Sample UP Artifact Relationships
Domain Model

Sale 1 1..* Sales


Business  . . .
LineItem
Modeling
date
. . .
. . . quantity

Vision
Use­Case Model

Process Sale
Process
Sale
use 1. Customer
case arrives ...
Cashier
names 2. Cashier
makes new
sale.
3. ... Glossary
parameters and 
Require­
Use Case Diagram Use Case Text return value details
ments
system
events

: System

Operation:  : Cashier
    enterItem(…) make Supplementary
system NewSale() Specification
Post­conditions: operations
enterItem
­ . . .
(id, quantity)

Operation Contracts System Sequence Diagrams

starting events to design for

Design Model
: Register : ProductCatalog : Sale

enterItem
Design (itemID, quantity)

spec = getProductSpec( itemID )

addLineItem( spec, quantity )

Hoa Sen University 138


What is System Sequence Diagram

 A diagram that shows, for ONE particular


scenario of a use case, the events that
external actors generate, their order, and
INTER-system events. (not detailed
method calls between objects)
 Describe what a system does without
explaining why

Hoa Sen University 139


System sequence diagram
system as black box

the name could be "NextGenPOS" but "System" keeps it 
simple

the ":" and underline imply an instance, and are explained in a 
later chapter on sequence diagram notation in the UML

external actor to  Process Sale Scenario
system

: Cashier :System

makeNewSale

a UML loop  loop [ more items ]


interaction  enterItem(itemID, quantity)
frame, with a 
boolean guard 
expression description, total

endSale a message with  
parameters
return value(s) 
associated with the  it is an abstraction 
previous message total with taxes
representing the 
system event of 
an abstraction that  entering the 
ignores presentation  makePayment(amount)
payment data by 
and medium    some mechanism
the return line is  change due, receipt
optional if nothing is 
returned

Hoa Sen University 140


Use Cases and SSDs

Process Sale Scenario
: Cashier :System

makeNewSale
Simple cash­only Process Sale scenario:
loop [ more items ]
1. Customer arrives at a POS checkout  enterItem(itemID, quantity)
with goods and/or services to purchase.
2. Cashier starts a new sale.
3. Cashier enters item identifier. description, total
4. System records sale line item and 
presents item description, price, and 
running total. 
Cashier repeats steps 3­4 until indicates 
done. endSale
5. System presents total with taxes 
calculated.
6. Cashier tells Customer the total, and  total with taxes
asks for payment.
7. Customer pays and System handles 
payment. makePayment(amount)
...

change due, receipt

Hoa Sen University 141


Choosing events and operation name

 System events should be expressed at the abstract level


of intention rather than in terms of the physical input
device

:System
: Cashier
better name
enterItem(itemID, quantity)

scan(itemID, quantity)

worse name

Hoa Sen University 142


Iterative and Evolutionary SSDs

 Do not create SSDs for all scenarios


(remember agile style)
 SSDs are part of the Use-Case Model
– Visualization of the interactions implied in the
use cases scenarios

Hoa Sen University 143


Operation Contract
Sample UP Artifact Relationships
Domain Model

Sale 1 1..* Sales


Business  . . .
LineItem
Modeling
date
. . .
. . . quantity

Vision
Use­Case Model

Process Sale
Process
Sale
use 1. Customer 
case arrives ...
Cashier
names 2. ...
3. Cashier 
enters item 
identifier. Glossary
Require­
Use Case Diagram Use Case Text
ments
ideas for  system
the domain  events requirements 
the post­
objects,  that must be 
conditions
attributes,  satisfied by 
: System
and  the software
associations  Operation:  : Cashier
that undergo      enterItem(…) make Supplementary
changes system NewSale() Specification
Post­conditions: operations
enterItem
­ . . .
(id, quantity)

Operation Contracts System Sequence Diagrams


starting events to 
design for, and 
more detailed 
requirements that  Design Model
must be satisfied  : Register : ProductCatalog : Sale
by the software
enterItem
Design (itemID, quantity)

spec = getProductSpec( itemID )

addLineItem( spec, quantity )

Hoa Sen University 144


Example Contract
 Contract CO2: enterItem

 Operation: enterItem(itemID: ItemID, quantity: integer)


 Cross References: Use Cases: Process Sale
 Preconditions: There is a sale underway.
 Postconditions:
– A SalesLineItem instance sli was created (instance creation).
– sli was associated with the current Sale (association formed).
– sli.quantity became quantity (attribute modification).
– sli was associated with a ProductDescription, based on itemID match
(association formed).

Hoa Sen University 145


Contract definition
 A description of each section in a contract is shown in the following
schema.

 Operation: Name of operation, and parameters


 Cross References: Use cases this operation can occur within
 Preconditions: Noteworthy assumptions about the state of the
system or objects in the Domain Model before
execution of the operation. These are non-
trivial assumptions the reader should be told.
 Postconditions: This is the most important section. The state of
objects in the Domain Model after completion
of the operation. Discussed in detail in a
following section.

Hoa Sen University 146


Contract procedure

 To make contract
– Identify System Operations from SSD
– For system operations that are complex or
subtle in their results or are not clearly
express in use cases, construct a contract
– To describe the post conditions, use the
following categories
 Instance creation and deletion
 Attribute change of value
 Associations (to be precise, UML links) formed and
broken
Hoa Sen University 147
System operations
Process Sale Scenario
:System
: Cashier
makeNewSale()

loop [ more items ]


enterItem(itemID, quantity) these input system events 
invoke system operations

the system event enterItem 
description, total invokes a system operation
called enterItem and so forth

this is the same as in object­
oriented programming when 
endSale() we say the message foo 
invokes the method (handling 
operation) foo
total with taxes

makePayment(amount)

change due, receipt

Hoa Sen University 148


Process Sale: makeNewSale
 Contract CO1: makeNewSale

 Operation: makeNewSale()
 Cross References: Use Cases: Process Sale
 Preconditions: none
 Postconditions:
– A Sale instance s was created (instance creation).
– s was associated with a Register (association formed).
– Attributes of s were initialized.

Hoa Sen University 149


Object design introduction
 How do developers design objects
– Code
– Design-while-coding
– Draw, then code
– Only draw
 Agile modelling: reduce drawing overhead and model to understand
and communicate
– Modeling with others
– Creating several models in parallel
– Using an internal wiki (www.twiki.org )
 How much time spent drawing UML before coding?
– For a three-week timeboxed iteration, spend a few hours or at most one day
near the start of the iteration drawing UML for the hard, creative parts of the
detailed object design

Hoa Sen University 150


Static vs. dynamic modelling

 Dynamic models help design the logic,


the behavior of the code or the method
bodies
– Sequence diagram, communication diagram
 Static models help design the definition
of packages, class names, attributes, and
method signatures
– UML class diagram

Hoa Sen University 151


Interaction diagrams

 Generalization of two more specialized


UML diagram types
– Sequence diagrams
– Communication diagrams
 Illustrate how objects collaborate via
messages and methods

Hoa Sen University 152


Sequence vs. Communication diagram

 Sequence diagrams
: A myB : B
illustrate interactions in a
doOne
kind of fence format doTwo

– Easier to see the call


doThree
sequence
– Large set of detailed notation
options
 Communication diagrams doOne
: A
illustrate interactions in a
graph or network format 1: doTwo

2: doThree
– More space-efficient
myB : B

Hoa Sen University 153


Common notation: participants –
lifeline box
lifeline box representing the class 
lifeline box representing a  Font, or more precisely, that Font is 
lifeline box representing an 
named instance an instance of class Class – an 
unnamed instance of class Sale
instance of a metaclass

«metaclass»
:Sale s1 : Sale
Font

List is an interface
lifeline box representing an  lifeline box representing 
instance of an ArrayList class,  one instance of class Sale,  in UML 1.x we could not use an 
parameterized (templatized) to  selected from the sales interface here, but in UML 2, this (or 
hold Sale objects ArrayList <Sale> collection an abstract class) is legal

sales:  x : List
sales[ i ] : Sale
ArrayList<Sale>

related 
example

Hoa Sen University 154


Sequence diagram notation

 Lifeline boxes
: Register : Sale
and lifelines
doX
 Messages doA

– Synchronous
doB
message a found message 
whose sender will not 
– Found message be specified doC

 Focus of control doD

and execution
execution specification 
specification bars bar indicates focus of 
control typical sychronous message 
shown with a filled­arrow line

Hoa Sen University 155


Sequence diagram notation
 Illustrating reply or returns
: Register : Sale
– Using the message syntax
returnVar = message(parameter).
doX
– Using a reply message line d1 = getDate
 Message to “self” or “this”
public class Register{ getDate

public void doX(){ aDate


clear();
… : Register

}
doX
public void clear(){
clear
}
}

Hoa Sen University 156


Sequence diagram notation
note that newly created 
: Register : Sale
objects are placed at their 

 Creation of instance creation "height"

– In implementation: makePayment(cashTendered)
create(cashTendered) : Payment

invoke the new authorize

operator and call the


constructor
 Object lifelines and
object destruction : Sale

create(cashTendered)
: Payment
– In language that the «destroy» stereotyped 
... message, with the large 
does not have X and short lifeline 
indicates explicit object 
garbage collection
«destroy»
X destruction

Hoa Sen University 157


Sequence diagram notation

 Diagram frames in UML sequence


diagrams
– Support conditional and looping construct

: A : B
makeNewSale

a UML loop  loop [ more items ]


enterItem(itemID, quantity)
frame, with a 
boolean guard 
expression description, total

endSale

Hoa Sen University 158


Sequence diagram notation

 Common frame operators


Frame Meaning
operator
Alt Alternative fragment for mutual exclusion
conditional logic expressed in the guards
Loop Loop fragment while guard is true
Opt Optional fragment that executes if guard is true
Par Parallel fragments that execute in parallel
Region Critical region within which only one thread can
run

Hoa Sen University 159


Sequence diagram notation

 Conditional messages
public class foo{ : Foo : Bar

Bar bar = new Bar(); xx

… opt [ color = red ]

public void m1(){ calculate

bar.xx();
if (color.equals(“red”)) yy

bar.calculate();
bar.yy(); : Foo : Bar
xx
}
}
[ color = red ] calculate

 UML1.x style
yy

Hoa Sen University 160


 Mutually exclusive
conditional messages
public class A{ : A : B : C
B b = new B();
doX
C c = new C();
public void doX(){ alt [ x < 10 ]
… calculate

if (x < 10)
b.calculate(); [ else ]
calculate
else
c.calculate();
}
}

Hoa Sen University 161


Sequence diagram notation

 Iteration over a collection

lineItems[i] :
: Sale This lifeline box represents one 
SalesLineItem
instance from a collection of many 
t = getTotal SalesLineItem objects. 

lineItems[i] is the expression to 
loop select one element from the 
[ i < lineItems.size ]
st = getSubtotal collection of many 
SalesLineItems; the ‘i” value 
refers to the same “i” in the guard 
i++
in the LOOP frame

an action box may contain arbitrary language 
statements (in this case, incrementing ‘i’)

it is placed over the lifeline to which it applies

Hoa Sen University 162


Sequence diagram notation
public class Sale{
private List<salesLineItem> lineItems = new ArrayList<salesLineItem>();
public Money getTotal(){
Money total = new Money();
Money subtotal = null;
for (SalesLineItem lineItem: lineItems){
subtotal = lineItem.getSubtotal();
total.add(subtotal);
}
lineItems[i] :
} : Sale
SalesLineItem
}
t = getTotal

loop
st = getSubtotal

Hoa Sen University 163


Sequence diagram notation

 Nesting frames
: Foo : Bar
xx

opt [ color = red ]

loop(n)
calculate

Hoa Sen University 164


Sequence diagram notation

 Relate interaction diagrams


 An interaction occurrence ( an interaction use) is
a reference to an interaction within another
interaction.
 Two related frames
– A frame around an entire sequence diagram, labelled
with the tag sd and a name,
– A frame tagged ref, called a reference, that refers to
another named sequence diagram;

Hoa Sen University 165


Sequence diagram notation
sd AuthenticateUser

: B : C
: A : B : C

authenticate(id)
doX
doA doM1
doB
doM2
authenticate(id) ref
AuthenticateUser

ref sd DoFoo
DoFoo

: B : C

interaction occurrence doX

note it covers a set of lifelines doY

note that the sd frame it relates to  doZ
has the same lifelines: B and C

Hoa Sen University 166


Sequence diagram notation

 Messages to classes to invoke static methods


public class Foo{
public void doX(){
Locale[] locales = Calendar.getAvailableLocales();
..
}
}

message to class, or a 
static method call

doX

1: locs = getAvailableLocales «metaclass»
: Foo
Calendar

Hoa Sen University 167


Sequence diagram notation
Payment {abstract}
Payment is an abstract  authorize() {abstract}
superclass, with concrete  ...
subclasses that implement the 
polymorphic authorize operation

CreditPayment DebitPayment
Polymorphic messages and cases authorize() authorize()
... ...

object in role of abstract 
polymorphic message
superclass

:Register :Payment {abstract}

doX
authorize stop at this point – don’t show any 
further details for this message

:DebitPayment :Foo :CreditPayment :Bar

authorize authorize
doA doX

doB

separate diagrams for each polymorphic concrete case

Hoa Sen University 168


Sequence diagram notation

 Asynchronous and synchronous calls


– Call does not wait for a response
– Asynchronous calls are used in multi-thread
application
– Show as a stick arrow message
– It is common for modeler to use stick arrow to
represent synchronous message
– Do not assume the shape of the arrow is correct

Hoa Sen University 169


Collaboration diagram notation
1: makePayment(cashTendered)
2: foo
 Links : Register :Sale
2.1: bar
– A connection path between two
objects
– Messages flow along link link line
 Messages
– Message between objects is
represented with a message
expression and small arrow
indicating the direction of the
message
– A sequence number is added to
show the sequential order of msg1
1: msg2
messages in the current thread 2: msg3
of control 3: msg4
: Register :Sale
– Many messages may flow 3.1: msg5
along a same single link

all messages flow on the same link

Hoa Sen University 170


Collaboration diagram notation (cont)
msg1

 Message to “self” or : Register

“this”
 Creation of instances 1: clear

– Use a message named


create message, with optional initializing parameters. This will
create for this purpose normally be interpreted as a constructor call.

 Create message may : Register


1: create(cashier )
:Sale

have parameters 1: create(cashier )

– Indicates a constructor
: Register :Sale {new}

call with parameters in «create»


1: make(cashier)
: Register :Sale
Java
if an unobvious creation message name is used , the
message may be stereotyped for clarity

Hoa Sen University 171


Collaboration diagram notation (cont)

 Message number sequencing


– OK to use flat numbering style or
– Nested decimal numbers
 Clarify whether a message is called within another
message
msg1 : A 1: msg2 : B

1.1: msg3
not numbered

legal numbering
: C

Hoa Sen University 172


Collaboration diagram notation (cont)
first second

third

msg1 : A 1: msg2 : B

1.1: msg3

2.1: msg5

2: msg4 : C

fourth fifth
2.2: msg6

sixth
: D

Hoa Sen University 173


Collaboration diagram notation (cont)

 Conditional messages
conditional message, with test
– A conditional message is message1

shown by following a 1 [ color = red ] :  calculate


: Foo : Bar
sequence number with a
conditional clause in
unconditional after 
square brackets. The either msg2 or msg4
: E 1a and 1b are mutually 
exclusive conditional paths

message is only sent if 2: msg6

the clause evaluates to msg1 : A


1a [test1] :  msg2
: B

true
1b [not test1] : msg4 1a.1: msg3
– Attach a letter to the
sequence number to : D 1b.1: msg5 : C

express mutually
exclusive message
Hoa Sen University 174
Collaboration diagram notation (cont)

 Iteration or Looping
– Use a “*” to signify iteration

runSimulation 1 * [ i = 1..n ]: num = nextInt
: Simulator : Random

iteration is indicated with a * and an optional 
iteration clause following the sequence number

Hoa Sen University 175


Collaboration diagram notation (cont)

 Iteration over a collection


t = getTotal 1 * [i = 1..n]: st = getSubtotal lineItems[i]:
: Sale
SalesLineItem

this iteration and recurrence clause indicates  This lifeline box represents one instance from a 
we are looping across each element of the  collection of many SalesLineItem objects. 
lineItems collection.
lineItems[i] is the expression to select one 
element from the collection of many 
SalesLineItems; the ‘i” value comes from the 
message clause.

t = getTotal 1 *: st = getSubtotal lineItems[i]:


: Sale
SalesLineItem

Less precise, but usually good enough to imply 
iteration across the collection members

Hoa Sen University 176


Collaboration diagram notation (cont)

 Messages to a Class Object

message to class, or a 
static method call

doX

1: locs = getAvailableLocales «metaclass»
: Foo
Calendar

Hoa Sen University 177


Collaboration diagram notation (cont)

Polymorphic messages and cases


stop at this point – don’t show any 
polymorphic message further details for this message

doX authorize object in role of abstract 


:Register :Payment {abstract} superclass

authorize authorize
doA
doX
doB
:DebitPayment :Foo :CreditPayment :Bar

separate diagrams for each polymorphic concrete case

Hoa Sen University 178


Collaboration diagram notation (cont)

 Asynchronous and Synchronous calls


startClock

3: runFinalization
:ClockStarter System : Class

1: create
asynchronous message
2: run

active object
:Clock

Hoa Sen University 179


Rectangle 8

Design class diagram

Lecture 5

Hoa Sen University 180


Agenda

 Notations
 Dependency
 Interaction and Class diagrams

Hoa Sen University 181


Design Class Diagram

 UML class diagram can be used in


multiple perspectives.
Domain Model Sale
Register Captures 1
1
time
conceptual 
... isComplete : Boolean
perspective
/total

Register Sale
Design Model ... time
1
isComplete : Boolean
DCD; software  endSale() currentSale /total
perspective enterItem(...)
makePayment(...) makeLineItem(...)

Hoa Sen University 182


Attributes in UML
Register Sale
using the attribute 
text notation to  ...
currentSale : Sale
indicate Register has 
a reference to one  ... ...
Sale instance

Register Sale
OBSERVE: this style 
visually emphasizes  1
... ...
the connection 
currentSale
between these classes ... ...

using the association notation to indicate 
Register has a reference to one Sale instance

Register Sale
thorough and 
unambiguous, but some  1
currentSale : Sale ...
people dislike the 
currentSale
possible redundancy ... ...

Hoa Sen University 183


Attributes in UML

 Attributes are usually assumed private if


no visibility is given
 Attributes-as-association line has
– A navigability arrow
– A multiplicity at the target end, but not the
source end
– A role name to show the attribute name
– No association Name

Hoa Sen University 184


Domain Model vs. DCD
the association name, common when drawing a 
domain model, is often excluded (though still legal) 
when using class diagrams for a software 
perspective in a DCD

Register Sale
UP Domain Model 1 Captures­current­sale 1
conceptual perspective id : Int time : DateTime

UP Design Model Register Sale


DCD 1
id: Int time: DateTime
software perspective currentSale
... ...

Hoa Sen University 185


Collection attributes
public class Sale{
private List <SalesLineItem> lineItems = new
ArrayList<SalesLineItem>();
}
Sale SalesLineItem
}
time: DateTime ...
lineItems : SalesLineItem [1..*]
                  or ...
lineItems : SalesLineItem [1..*] {ordered}

...
Two ways to show a 
collection attribute

Sale SalesLineItem
1..*
time: DateTime ...
lineItems
... {ordered, List} ...

notice that an association end can optionally also  
have a property string such as {ordered, List}

Hoa Sen University 186


Methods
 Method signature is shown in the third compartment of
UML class box
 Should correspond with the messages in interaction
diagram

Register
«method»
// pseudo­code or a specific language is OK ...
public void enterItem( id, qty )
{ endSale()
   ProductDescription desc = catalog.getProductDescription(id); enterItem(id, qty)
   sale.makeLineItem(desc, qty); makeNewSale()
} makePayment(cashTendered)

Hoa Sen University 187


Note Symbol & Operation issues

 Note Symbols
– May represent several things
 A UML note or comment
 A UML constraint
 A method body

 Operation issues in DCDs


– The create operation (Constructor)
 See example in the SuperclassFoo class
– Operations to access attributes
 Common to ignore them.

Hoa Sen University 188


Keywords
 A UML keyword is a textual adornment to categorize a
model element
 Usually show in guillemet (« »), sometimes are shown in
curly braces.
 It is OK to define your own keyword
 Many people use it same as stereotype or tag in UML 1

Keyword Meaning Example usage


{abstract} Classifier is an abstract In class diagram, above
class classifier name
«interface» Classifier is an interface In class diagram, above
classifier name

Hoa Sen University 189


Generalization, abstract class,
abstract operation
 In DCD generalization implies inheritance
from the super class to subclass
 Abstract class and operations can be
shown with an {abstract} keyword or by
italicizing the name
 Final classes and operations are shown
with the {leaf} keyword

Hoa Sen University 190


Dependency

 A dependency exists between two elements if


changes to the definition of one element (the
supplier) may cause changes to the other (the
client)
 Various reason for dependency
– Class send message to another
– One class has another as its data
– One class mention another as a parameter to an
operation
– One class is a superclass or interface of another

Hoa Sen University 191


When to show dependency

 Be selective in describing dependency


 Many dependencies are already shown in
other format
 Use dependency to depict global,
parameter variable, local variable and
static-method.
 Use dependencies when you want to
show how changes in one element might
alter other elements
Hoa Sen University 192
Dependency example
public class Sale {
public void updatePriceFor(
ProductionDescription desc) {
Money basePrice = desc.getPrice();
//... the Sale has parameter visibility to a 
ProductDescription, and thus some kind of 
} dependency
} ProductDescription

...
Sale
...
...

updatePriceFor( ProductDescription )
... SalesLineItem

1..* ...
lineItems
...

Hoa Sen University 193


Dependency example (cont)
public class Foo{
public void doX(){
System.runFinalization();
//..
} the doX method invokes the runFinalization 
} static method, and thus has a dependency on 
the System class
System

...
Foo
runFinalization()
... ...

doX()
...

Hoa Sen University 194


Dependency labels

 There are many varieties of dependency,


use keywords to differentiate them
 Different tools have different sets of
supported dependency keywords.
– <<call>> the source calls an operation in the
target
– <<use>> the source requires the targets for
its implementation
– <<parameter>> the target is passed to the
source as parameter.
Hoa Sen University 195
Interface

 Abstract definition of purely functional


interfaces
 They do not define any attributes or
associations
 They have no instances.
 They define a set of abstract operations
 They are an important aid for dividing
software development between different
teams (design by contract)

Hoa Sen University 196


Constraints

three ways to show UML constraints

Stack

size : Integer { size >= 0 }

push( element ) { post condition: new size = old size + 1 }


pop() : Object

{
post condition: new size = old size – 1
}

Hoa Sen University 197


Template Classes
public class Board{
private List <Square> squares = new
ArrayList<Square>();
the attribute type may be expressed in 
parameterized or template 
//.. K official UML, with the template binding 
interfaces and classes  «interface» syntax requiring an arrow
List                 or
} K is a template parameter  in another language, such as Java
clear()
...

Board

squares : List<K   Square>
anonymous class with                   or
template binding complete T squares : List<Square>
ArrayList ...
elements : T[*]
ArrayList<T   Square> ...
clear() clear()
... for example, the elements attribute is an 
...
array of type T, parameterized and bound 
before actual use.
there is a chance the UML 2 “arrow” symbol will 
eventually be replaced with something else e.g., ‘=’

Hoa Sen University 198


User-defined compartments
DataAccessObject

id : Int
...

doX()
...

exceptions thrown
DatabaseException
IOException

responsibilities
serialize and write objects
read and deserialize objects
...

Hoa Sen University 199


Interaction and Class Diagrams
: Register : Sale

makePayment(cashTendered) 

makePayment(cashTendered)

messages in interaction 
diagrams indicate operations 
in the class diagrams classes 
identified in the 
interaction 
diagrams are 
Register Sale declared in the 
1 class diagrams
... ...
currentSale
makePayment(…) makePayment(…)
... ...

Hoa Sen University 200


Rectangle 8

Object Design

Lecture 6

Hoa Sen University 201


Agenda

 Object design basics


 Monopoly game design and GRASP
principles introduction
 GRASP principles in POS projects

Hoa Sen University 202


Object Design

 “Identify requirements, create a domain model,


add methods to the software classes, define
messages to meet requirements…”
 Too Simple!
– What methods belong where?
– How do we assign responsibilities to classes?
 The critical design tool for software development
is a mind well educated in design principles and
patterns.

Hoa Sen University 203


Object Design: input

 POS project inputs


– Use case text of Process Sale
 Defines the behaviour
– System sequence diagram
 Identify the system operation messages
– Supplementary specification
 Defines non-functional goals
– Glossary
 Data format, data related with UI and database
– Domain model
 initial attempt of software object in the domain layer of
software architecture

Hoa Sen University 204


Object Design: activities and output

 Design activities
– Coding immediately
 Using test-driven development
– Short UML modelling
 Apply OO Design principles and design patterns
 Design output
– UML diagrams for difficult parts of the system
– UI prototypes and database models

Hoa Sen University 205


Responsibilities
 Contract or obligation of a class
 What must a class “know”? [knowing responsibility]
– Private encapsulated data
– Related objects
– Things it can derive or calculate
 What must a class “do”? [doing responsibility]
– Take action (create an object, do a calculation)
– Initiate action in other objects
– Control/coordinate actions in other objects
 Responsibilities are assigned to classes of objects during
object design

Hoa Sen University 206


Examples of responsibilities

 “A Sale is responsible for creating


SalesLineItems” (doing)
 “A Sale is responsible for knowing its total”
(knowing)
 These are related to operations, attributes,
associations in the domain model

Hoa Sen University 207


Domain model and responsibilities

 Domain model illustrates attributes and


associations => inspires the “knowing”
responsibilities
 Responsibilities are defined in conceptual
level
 Methods fulfil responsibilities
– Alone
– Through collaboration with other objects and
methods

Hoa Sen University 208


Responsibilities and UML

: Sale

makePayment(cashTendered)
create(cashTendered) : Payment

abstract, implies Sale objects have a 
responsibility to create Payments

Hoa Sen University 209


GRASP principles

 General Responsibility Assignment


Software Patterns
 The five basic principles in Monopoly
game design:
– Creator
– Information Expert
– High Cohesion
– Low Coupling
– Controller

Hoa Sen University 210


Creator: problem

 Problem
– Who creates the Square object
 Start point: domain model

Hoa Sen University 211


Creator: principle

 Problem
– Who creates an A object
 Solution
– Assign class B the responsibility to create an
instance of class A if one of these is true
 B “contains” A
 B records A
 B closely uses A
 B has the Initializing data for A

Hoa Sen University 212


Creator: Solution

Hoa Sen University 213


Information Expert
 Problem
– Who knows about a Square object, given a key?
– Alternatively, who should be the receiver of message
getSquare(name)
 Board knows about all squares
– Board has the information necessary to fulfil this responsibility

Hoa Sen University 214


Information Expert: principle

 Problem
– What is a general principle of assigning
responsibilities to objects
 Solution
– Assign a responsibility to the class that has
the information needed to fulfil it

Hoa Sen University 215


Low coupling

 Problem
– How to reduce the impact of change, to
support low dependency, and increase reuse?
 Solution
– Assign a responsibility so that coupling
remains low

Hoa Sen University 216


Coupling

 How strongly one element is


connected to, has knowledge of, or
depends on other elements
 Illustrated as dependency relationship
in UML class diagram

Hoa Sen University 217


Example of poor design

Hoa Sen University 218


Controller

 Problem
– What first object beyond the UI layer receives and
coordinates (“controls”) a system operation
 Solution
– Assign the responsibility to an object representing one
of these choices
– Represents the overall system, root object, device or
subsystem
– Represents a use case scenario within which the
system operations occurs

Hoa Sen University 219


Example

Hoa Sen University 220


Example

Hoa Sen University 221


Example

Hoa Sen University 222


High cohesion

 Problem
– How to keep objects focused,
understandable, and manageable, and as a
side effect, support Low Coupling?
 Solution
– Assign responsibilities so that cohesion
remains high

Hoa Sen University 223


Cohesion

 How strongly related and focused the


responsibilities of an element are
 Formal definition (calculation) of cohesion
– Cohesion of the two methods is defined as the
intersection of the sets of instance variables that are
used by the methods
– If an object has different methods performing different
operations on the same set of instance variables, the
class is cohesive

Hoa Sen University 224


Example

Hoa Sen University 225


Applying GRASP to POS design
Sale

 Creator time

– Example: Who Contains

should be 1..*
Product
Sales Description
responsible for LineItem * Described­by 1
description
creating a quantity price
itemID

SalesLineItem : Register : Sale

instance
makeLineItem(quantity)
– Solution: Sale create(quantity)
: SalesLineItem

contains many
SalesLineItem
objects.
Hoa Sen University 226
GRASP in POS project

 Information Expert
Sale
 Example
time
– Who should be 1
responsible for Contains
knowing the grand
1..*
total of a sale Product
Sales Description
– What information do LineItem * Described­by 1
description
quantity price
we need to compute itemID
the grand total
 SalesLineItem

Hoa Sen University 227


Create diagrams in parallel

t = getTotal :Sale Sale

time
...

New method getTotal()

The new responsibility is conveyed by an operation in an


interaction diagram. A new method is created in the design
class to express this.

Hoa Sen University 228


Create diagram in parallel
this notation will imply we 
are iterating over all 
elements of a collection Sale

time
...
t = getTotal 1 *: st = getSubtotal lineItems[ i ] : 
: Sale getTotal()
SalesLineItem

SalesLineItem

quantity

New method getSubtotal()

 Responsibility for each subtotal is


assigned to the SalesLineItem

Hoa Sen University 229


Create diagrams in parallel
Sale

time
...
t = getTotal 1 *: st = getSubtotal lineItems[ i ] :
: Sale getTotal()
SalesLineItem

1.1: p := getPrice() SalesLineItem

quantity
:Product getSubtotal()
Description

Product
 Responsibility for each item price is assigned to the Description
ProductSpecification description
price
itemID
New method getPrice()

Hoa Sen University 230


GRASP in POS projects

 How should we assignment


responsibilities of creating Payment
instance and associate it with the Sale.

Hoa Sen University 231


Options

makePayment()  1: create() 
: Register p : Payment

2: addPayment(p) 
:Sale

makePayment()  1: makePayment() 
: Register :Sale

1.1. create() 

:Payment

Hoa Sen University 232


GRASP in POS project

presses button

: Cashier

actionPerformed( actionEvent )

system operation message
UI Layer :SaleJFrame

1: enterItem(itemID, qty)

controller

Domain Layer 1.1: makeLineItem(itemID, qty)
:Register :Sale

Hoa Sen University 233


Controller Choices

 Represents the
overall “system”, enterItem(id, quantity) 
:Register
“root object”,
device or
subsystem enterItem(id, quantity) 
:ProcessSaleHandler
– Register
 Represents a
receiver or handler
of all system
events of a user
case scenario
Hoa Sen University 234
Allocate system operations
System Register

endSale() ...
enterItem()
makeNewSale() endSale()
makePayment() enterItem()
makeNewSale()
makeNewReturn() makePayment()
enterReturnItem()
. . . makeNewReturn()
enterReturnItem()
. . .

system operations  allocation of system 
discovered during system  operations during design, 
behavior analysis using one facade controller

ProcessSale HandleReturns
System Handler Handler

endSale() ... ...


enterItem()
makeNewSale() endSale() enterReturnItem()
makePayment() enterItem() makeNewReturn()
makeNewSale() . . .
enterReturnItem() makePayment()
makeNewReturn()
. . .

allocation of system 
operations during design, 
using several use case 
controllers

Hoa Sen University 235


Choosing a Controller

 Façade controller
– PRO: all events handled in one place
– CON: can become too bloated
 Use-case controller
– PRO: manage many different events across
different processes
– CON: adds additional classes; events can’t be
managed (e.g. logged) in one place

Hoa Sen University 236


Desirable coupling of UI layer to
domain layer

presses button

: Cashier

actionPerformed( actionEvent )

system operation message
UI Layer :SaleJFrame

1: enterItem(itemID, qty)

controller

Domain Layer 1.1: makeLineItem(itemID, qty)
:Register :Sale

Hoa Sen University 237


Less desirable coupling

presses button

Cashier

actionPerformed( actionEvent )

It is undesirable for an interface
layer object such as a window to get 
UI Layer :SaleJFrame involved in deciding how to handle 
domain processes.

Business logic is embedded in the 
presentation layer, which is not useful.

1: makeLineItem(itemID, qty)
Domain Layer :Sale

SaleJFrame should not 
send this message.

Hoa Sen University 238


High cohesion
 Reconsider the problem presented and solved by “Low
coupling” principle
: Register : Sale

makePayment()
create()
p : Payment

addPayment( p )

From previous practice, Register is mainly responsible for handling System


operations such as enterItem, endSale, and so on; The responsibility of creating
payment instance is not cohesive with other responsibilities
Hoa Sen University 239
Desirable solution

: Register : Sale

makePayment()
makePayment()
create()  : Payment

Hoa Sen University 240


Rectangle 8

Use case realization

Lecture 7

Hoa Sen University 241


Agenda

 Recap
 Use Case Realization with GRASP
– POS project
– Monopoly Game project
 Designing for visibility

Hoa Sen University 242


Recap

 Design Class Diagram


– DCD vs. DM
– Four different types of notations indicating
inter-class relationship
 GRASP
– Assigning Responsibilities to classes
 Some object needs to be created
 Some action needs to be taken

Hoa Sen University 243


Use-Case Realization

 “…describes how a particular use case is


realized within the design model, in terms
of collaborating objects” [RUP]
 Individual scenarios are realized

Use case -> System events -> System sequence diagram ->
System operation contracts -> Interaction diagrams -> Design classes

Hoa Sen University 244


System operation
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

makeNewSale 1: ???
:Register
Window objects 
or 
GUI widget objects . . . enterItem
:Register
1: ???
or
Web control objects
endSale 1: ???
:Register

makePayment :Register 1: ???

UI LAYER DOMAIN LAYER

The system operations in the SSD are used as the start messages into the domain layer
If communication diagrams are used, one per system operation
Same for sequence diagram

Hoa Sen University 245


One diagram per system operation

: Register

makeNewSale
create
: Sale

Window objects 
or 
GUI widget objects . . .
or
Web control objects
: Register : ProductCatalog

enterItem(...)
desc = getProductDesc( itemID )

. . .

UI LAYER DOMAIN LAYER

Hoa Sen University 246


Design makeNewSale

 Choosing the controller class


– A façade controller is satisfactory if there are
only a few system operations
– Use Register here.
 Creating a new Sale
– Register create Sale
– Sale create a collection to store
SalesLineItems

Hoa Sen University 247


Design makeNewSale
by Creator 
and 
Controller Register creates a 
Sale by Creator by Creator, Sale 
:Register creates an empty 
collection (such as a 
List) which will 
eventually hold 
SalesLineItem 
instances
makeNewSale
create
:Sale

create lineItems :
List<SalesLineItem>

this execution specification is implied to be 
within the constructor of the Sale instance

Hoa Sen University 248


Design: enterItem
 Contract CO2: enterItem
 Operation: enterItem(itemID : ItemID, quantity : integer)
 Cross References: Use Cases: Process Sale
 Preconditions: There is an underway sale.
 Postconditions:
– A SalesLineItem instance sli was created (instance creation).
– sli was associated with the current Sale (association formed).
– sli.quantity became quantity (attribute modification).
– sli was associated with a ProductDescription, based on itemID match
(association formed).

Hoa Sen University 249


Design enterItem

 Choosing controller class


 Display item description and price (ignore
at this stage)
 Create a new SalesLineItem
 Finding a ProductDescription
 Visibility to ProductCatalog
 Temporary and persistent storage
– We can defer database design and use
temporary memory object instead
Hoa Sen University 250
Design enterItem
by Creator
by Controller

enterItem(id, qty) 2: makeLineItem(desc, qty)
:Register :Sale

1: desc = getProductDesc(id) 2.1: create(desc, qty)

:Product
by Expert
Catalog

sl: SalesLineItem
1.1: desc = get(id)
2.2: add(sl)

lineItems : 
: Map<ProductDescription> add the newly created 
List<SalesLineItem>
SalesLineItem instance to the List

Hoa Sen University 251


Partial Design Class Diagram

ProductDescription
ProductCatalog descriptions
{Map} description : Text
... price : Money
1 1..* itemID: ItemID
catalog getProductDesc(...)
...

description 1
Sale
Register isComplete : Boolean
time : DateTime lineItems SalesLineItem
... currentSale {ordered}
makeLineItem(...) quantity : Integer
enterItem(...) 1 1..*
...
... ...

Hoa Sen University 252


Design endSale

«method»
public void getTotal()
{
   int tot = 0;
   for each SalesLineItem, sli
          tot = tot + sli.getSubtotal();
   return tot
}

tot = getTotal 1 *[ i = 1..n]: st = getSubtotal lineItems[ i ] :


:Sale
SalesLineItem

1.1: pr = getPrice

:ProductDescription

Hoa Sen University 253


Design makePayment
 Contract CO4: makePayment
 Operation: makePayment( amount: Money )
 Cross References: Use Cases: Process Sale
 Preconditions: There is an underway sale.
 Postconditions:
– A Payment instance p was created (instance creation).
– p.amountTendered became amount (attribute modification).
– p was associated with the current Sale (association formed).
– The current Sale was associated with the Store (association formed); (to add it to
the historical log of completed sales).

Hoa Sen University 254


Design makePayment

 Creating payment
by Controller by Creator and Low Coupling

makePayment(cashTendered)  1: makePayment(cashTendered)
:Register :Sale

1.1: create(cashTendered)

:Payment

Hoa Sen University 255


Design makePayment
Sale Sale

 Logging a sale ... ...

... ...

* *
Logs­completed Logs­completed

1 1

Store SalesLedger

... ...

addSale(s : Sale) addSale(s : Sale)
... ...

Store is responsible for 
SalesLedger is responsible 
knowing and adding 
for knowing and adding 
completed Sales.
completed Sales.
Acceptable in early 
Suitable when the design 
development cycles if the 
grows and the Store 
Store has few  
becomes uncohesive.
responsibilities.

Hoa Sen University 256


Design makePayment

note that the Sale instance is named
's' so that it can be referenced as a 
parameter in messages 2 and 2.1

makePayment(cashTendered)  1: makePayment(cashTendered)
:Register s :Sale

2: addSale(s) 1.1: create(cashTendered)

by Expert
:Payment
:Store

2.1: add(s)

completedSales: 
List<Sale>

Hoa Sen University 257


Design makePayment

 Calculating the balance


– Who is responsible for knowing the balance?
 To calculate, sale total and payment tendered are
required
 Sale and Payment are partial Experts
 Consider coupling…
– Sale already has visibility into Payment
– Payment does not have visibility into Sale
– Giving Sale primary responsibility doesn’t
increase overall coupling
Hoa Sen University 258
getBalance design

{ bal = pmt.amount ­ s.total }

bal = getBalance s :Sale 1: amt = getAmount pmt: Payment

2: t = getTotal

Hoa Sen University 259


Object Design: startUp
 Initial system operation
 Delay until all other system operations have been
considered
– What objects need to be there through out the use case
– What associations need to be there through out the use case
 Create a set of domain objects that need to be there to
support the use case execution
 Find a suitable initial object and request that object to
create a set of other objects
 Do the initialization design last

Hoa Sen University 260


Create Initial Domain Object
public class Main {
public static void main( String[] args ) {
// Store is the initial domain object.
// The Store creates some other domain objects.
Store store = new Store();
Register register = store.getRegister();
ProcessSaleJFrame frame =
new ProcessSaleJFrame( register ); ...
}
}

Hoa Sen University 261


Designing Store.create()

 Create: Store, Register,


ProductCatalog,ProductSpecifications
 Associate: ProductCatalog with
ProductSpecifications; Store with
ProductCatalog; Store with Register;
Register with ProductCatalog

Hoa Sen University 262


Designing Store.create()
pass a reference to the ProductCatalog to the 
Register, so that it has permanent visibility to it

create 2: create(pc) 
:Store :Register

by Creator
create an empty 
collection object
1: create
1.1: create

pc: 1.2.2*: put(id, pd)  descriptions:


ProductCatalog Map<ProductDescription>

1.2.1*: create(id, price, description) 
1.2: loadProdSpecs() 

pd:
the * in sequence number indicates the  ProductDescription
message occurs in a repeating section

Hoa Sen University 263


Monopoly game project

 Two system
operations in the first
iteration
– Initialize
 Ignore at this state
– Play game
 Main focus

Hoa Sen University 264


Design playGame

 Choosing the
Controller Class
– Represents the overall
“system”, “root object”
 MonopolyGame? *
– Represents a receiver
or handler of all system
events of a use case
scenario
 PlayGameHandler?

Hoa Sen University 265


Game-Loop algorithm

 Terminology
 turn – a player rolling the dice and moving
the piece
 round – all the players taking one turn
 Game loop
for N rounds
for each player p
p takes a turn

Hoa Sen University 266


Who is responsible for controlling
the game loop
Information needed Who has this information
The current round count No object has it yet, assigning this to the
MonopolyGame object is justifiable
All players MonopolyGame object

Hoa Sen University 267


Who takes a turn?

 When there are multiple partial information


experts to choose from
– Place the responsibility in the dominant information expert
– If the first guideline does not apply, consider the coupling and
cohesion impact of each and choose the best
– Consider possible future evolution
– Taking a turn might involve buying property, deposit money in
bank.. Etc. A player should have all information regarding those
activities
Information Needed Who has the information
Current location of the player Player
Two die objects MonopolyGame
All the squares Board

Hoa Sen University 268


Partial design diagrams

Hoa Sen University 269


Taking a turn refine

 Taking a turn involves


– Calculating the face value of two die
– Calculating the new square location
– Moving the player’s piece from an old location to a
new location
 Who coordinate all this
– Player
 Visibility problem
– Player must have references to all those objects

Hoa Sen University 270


Taking a turn

Hoa Sen University 271


Command-Query Separation Principle

 Style 1#  Every method should


public void roll(){ either be:
faceValue = //random num
– A command method that
generation
performs an action often has
}
side effects such as changing
public int getFaceValue(){
the state of objects and is void.
return faceValue;
– A query that returns data to the
}
caller and has no side effects –
 Style 2# it should not permanently
public int roll(){ change the state of any objects.
faceValue = //random num  But a method should not
generation
return faceValue; be both
}

Hoa Sen University 272


Static design for playGame

Hoa Sen University 273


Initialization and the start up use
case

Hoa Sen University 274


Visibility between objects
class Register
{
  ...
  private ProductCatalog catalog;
  ...
}

: Register : ProductCatalog
enterItem
(itemID, quantity)
desc = getProductDesc( itemID )

public void enterItem( itemID, qty )

  ...
  desc = catalog.getProductDesc(itemID)
  ...
}

Hoa Sen University 275


What is visibility

 Ways in which A can have visibility into B:


– Attribute Visibility
B is an attribute of A
– Parameter Visibility
B is a parameter of a method of A
– Local Visibility
B is a (non-parameter) local object in a
method of A
– Global visibility
B is in some way globally visible

Hoa Sen University 276


Attribute Visibility

class Register public void enterItem(itemID, qty)
{ { 
  ...   ...
  private ProductCatalog catalog;   desc = catalog.getProductDesc(itemID)
  ...   ...
} }

: Register : ProductCatalog
enterItem
(itemID, quantity)
desc = getProductDesc( itemID )

Hoa Sen University 277


Parameter Visibility

enterItem(id, qty) 2: makeLineItem(desc, qty)
:Register :Sale

1: desc = getProductDesc(id)
2.1: create(desc, qty)

:Product
Catalog

makeLineItem(ProductDescription desc, int qty) sl : SalesLineItem

  ...
  sl = new SalesLineItem(desc, qty);
  ...
}

Hoa Sen University 278


Parameter to attribute visibility

enterItem(id, qty)
2: makeLineItem(desc, qty)
:Register :Sale

2: desc = getProductDesc(id)
2.1: create(desc, qty)

:Product
Catalog

sl : SalesLineItem
// initializing method (e.g., a Java constructor)
SalesLineItem(ProductDescription desc, int qty)

...
description = desc;  // parameter to attribute visibility
...
}

Hoa Sen University 279


Local visibility
 Local visibility from A to B exists when B is declared as a
local object with in a method of A
– Create a new local instance and assign it to a local variable
– Assign the returning object from a method invocation to a local
variable
 Variable desc of type ProductionDescription is a local variable of
enterItem method
enterItem(id, qty)

...
// local visibility via assignment of returning object
ProductDescription desc = catalog.getProductDes(id);
...
}

: Register : ProductCatalog
enterItem
(itemID, quantity)
desc = getProductDesc( itemID )

Hoa Sen University 280


Global visibility

 Global visibility from A to B exists when B


is global to A;
 Permanent visibility as it persists as long
as A and B exist
– Global variable
– Singleton pattern

Hoa Sen University 281

Вам также может понравиться