iteration 1 object-oriented analysis and design
TRANSCRIPT
Object-Oriented Analysis and Object-Oriented Analysis and DesignDesignwith Patterns, Process, and the UMLwith Patterns, Process, and the UML
IntroductionIntroduction
IntroductionIntroduction
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 ObjectivesOverview 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 componentsAssessment components
Hoa Sen University 4
Team workTeam 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 Team Project – Collaborative Tagging SystemTagging 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 usersManage contents and their tagsProduce summaries upon request
Hoa Sen University 6
Project TaskProject 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 Software
Microsoft Visio– Licensed software– Installed on the lab PC
Hoa Sen University 8
What is OOAD?What is OOAD?
Lecture 1Lecture 1
Hoa Sen University 9
Today’s lecture topicToday’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 DesignWhat 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?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 AnalysisObject vs. Function Oriented Analysis
Hoa Sen University 13
Library Information
System
Structured A&DDecompose by functions and processes
OOA&DDecompose by objects and concepts
Catalogue Librarian
Book Library
Functional DecompositionFunctional 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 DecompositionFunctional 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 thingsHow 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” optionA “software like” option
Steps:– Get list of people in the class– For each person on this list,
do the following: Find the next class he or she
is taking Find the location of that class Find the way to get from your
classroom to the persona’s next class
Tell the person how to get to his or her next class
Procedures needed:– A way of getting the list of
people in the class– A way of getting the schedule
for each person in the class– A program that gives
someone directions from your classroom to any other classroom
– A control program that works for each person in the class and does the required steps for each person
Hoa Sen University 17
A “human like” optionA “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?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 Dealing with changing requirementsrequirements
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 changingDealing with changingrequirementsrequirements
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]Key Steps in OOAD [1]
Hoa Sen University 22
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.
Key steps in OOAD [2]Key steps in OOAD [2]
a domain model that shows the noteworthy domain concepts or objects, attributes, and associations
Hoa Sen University 23
Player
name
DiceGame
Die
faceValue
Rolls
Plays
Includes
2
2
1
1
1
1
Key steps in OOAD [3]Key steps in OOAD [3]
Interaction Diagram: shows the flow of messages between software objects (method invocation)
Hoa Sen University 24
:DiceGame
play()
die1 : Die
fv1 := getFaceValue()
die2 : Die
roll()
roll()
fv2 := getFaceValue()
Key steps in OOAD [4]Key steps in OOAD [4]
Class Model: shows attributes, methods and associations for software (solution) objects (not domain objects!)
Hoa Sen University 25
2
Die
faceValue : int
getFaceValue() : introll()
DiceGame
die1 : Diedie2 : Die
play()
1
Iterative and Evolutionary Iterative and Evolutionary DevelopmentDevelopment
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 Iterative and evolutionary developmentdevelopment
Hoa Sen University 27
Requirements
Design
Implementation &Test & Integration
& More Design
Final Integration & System Test
Requirements
Design
3 weeks (for example)
The system grows incrementally.
Feedback from iteration N leads to refinement and adaptation of the requirements and design in iteration N+1.
Iterations are fixed in length, or timeboxed.
Time
Implementation &Test & Integration
& More Design
Final Integration & System Test
Handle change on iterative projectHandle change on iterative project
Hoa Sen University 28
Early iterations are farther from the "true path" of the system. Via feedback and adaptation, the system converges towards the most appropriate requirements and design.
In late iterations, a significant change in requirements is rare, but can occur. Such late changes may give an organization a competitive business advantage.
one iteration of design, implement, integrate, and test
How long should an iteration be?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 How to do Iterative and Evolutionary Analysis and Design?Analysis and Design?
Hoa Sen University 30
Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5
20%
2%
requ
irem
ent
s
soft
war
e
30%
5%re
quire
me
nts
soft
war
e
50%
8%
90% 90%
20%10%
requirements workshops
Imagine this will ultimately be a 20-iteration project.
In evolutionary iterative development, the requirements evolve over a set of the early iterations, through a series of requirements workshops (for example). Perhaps after four iterations and workshops, 90% of the requirements are defined and refined. Nevertheless, only 10% of the software is built.
1 2 3 4 5 ... 20
week 1
M T W Th F
week 2
M T W Th F
week 3
M T W Th F
kickoff meeting clarifying iteration goals with the team. 1 hour
team agile modeling & design, UML whiteboard sketching.5 hours
start coding & testing
a 3-week iteration
de-scope iteration goals if too much work
final check-in and code-freeze for the iteration baseline
demo and 2-day requirements workshop
next iteration planning meeting;2 hours
Most OOA/D and applying UML during this period
Use-case modeling during the workshop
Agile Methods and attitudesAgile 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 ModellingAgile 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)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 studyLayers and textbook case study
Hoa Sen University 34
User Interface
Sale Payment
Logging ... Database Access ...
application logic layer
other layers or components
minor focus
explore how to connect to other layers
primary focus of case studies
explore how to design objects
secondary focus
Case study strategyCase study strategy
Hoa Sen University 35
Iteration 1
Iteration 2
Iteration 3Introduces just those analysis and design skills related to iteration one.
Additional analysis and design skills introduced.
Likewise.
CasesCases
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
InceptionInception
Lecture 2Lecture 2
Hoa Sen University 37
AgendaAgenda
Recap Inception overview Evolutionary Requirements Use cases Other requirements Assignment 1 instruction
Hoa Sen University 38
What we learned last weekWhat 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 QuestionsInception 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 InceptionGoals 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 InceptionArtefacts in InceptionArtefacts Comments
Vision and Business Case
Describe the high-level goals and constraints, the business case, and 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 specification
Other requirements
Glossary Key domain terminology, and data dictionary
Risk List & Risk Management plan
Describes the risks (business, technical, resource, schedule) and ideas for their mitigation or response
Prototypes and proof-of-concepts
To clarify the vision, and validate technical ideas
Iteration Plan Describes what to do in the first elaboration iteration
Phase Plan & Software Development plan
Low-precision guess for elaboration phase duration and effort. Tools, 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 ifIt 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 RequirementsUnderstanding 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 Evolutionary vs. Waterfall requirementsrequirements
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+ ModelThe 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+ ModelThe FURPS+ Model
Implementation – resource limitations, languages/tools, hardware
Interface – with legacy systems Operations – sysop management Packaging – delivery, installation Legal – licensing, etc.
Hoa Sen University 48
Use FURPS+ as a global checklist when identifyingrequirements for a system you are designing
Other TerminologyOther 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 RequirementsDocument 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 ModelThe 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
StoriesStories
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.
Hoa Sen University 52
Usually, writing the stories is more important thandiagramming a use case model in UML
DefinitionsDefinitions
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
ExamplesExamples
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?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 formatsCommon 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 exampleNextGen 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 ...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…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…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 checkout2.Cashiers starts a new sale3.Cashier enters item identifier4.System record sales line item…
– Cashier repeats steps 3-4 until indicates done.5.System presents total with taxes calculated
Hoa Sen University 60
Details…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 sale2. 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…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 1Guidelines 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 2Guideline 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 3Guideline 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)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 boundaryChoose 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 goalsFind primary actor and goals
Questions to help find actors and goals– Is “time” an actor because
the system does something in response to a time event?
– In addition to human primary actors, are there any external software or robotic systems that call upon services of the system?
– …
Actor Goals
Cashier Process salesProcess rentalsHandle returns
Manager Start upShut down
System Admin Add userModify user
SalesactivitySystem
Analyse sales andperformance data
Hoa Sen University 68
Actors, Goals & BoundariesActors, Goals & Boundaries
Hoa Sen University 69
Goal: Process sales
Cashier
Customer
POS System
Checkout Service
Goal: Buy items
Enterprise Selling Things
Sales TaxAgency
Goal: Collect taxes on sales Sales Activity
System
Goal: Analyze sales and performance data
Valid or useful use casesValid 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: TestsGuideline 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)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 DiagramApplying UML: Use Case Diagram
Hoa Sen University 73
NextGen POS
Manage Users
. . .
Cashier
SystemAdministrator
actor
use case
communicationsystem boundary
PaymentAuthorization
Service
«actor»Tax Calculator
«actor»Accounting
System
alternatenotation for a computer system actor
«actor»HR System
Cash In
«actor»Sales Activity
System
Manage Security
Analyze Activity
Customer
Manager
Process Sale
Handle Returns
Use case diagram is anExcellent picture of thesystem context. It servesas a communication toolthat summarizes thebehaviour of a system andits actors
Diagram notationDiagram notation
Hoa Sen University 74
NextGen
Process Sale
. . .Cashier
Show computer system actors with an alternate notation to human actors.
primary actors on the left
supporting actors on the right
For a use case context diagram, limit the use cases to user-goal level use cases.
«actor»Payment
AuthorizationService
Alternate actor notationAlternate actor notation
Hoa Sen University 75
NextGen
Process Sale
«system»Payment
AuthorizationService
...
«actor»Payment
AuthorizationService
Some UML alternatives to illustrate external actors that are other computer systems.
The class box style can be used for any actor, computer or human. Using it for computer actors provides visual distinction.
PaymentAuthorization
Service
The The includeinclude relationship 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 relationshipExample 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 caseIncluded 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 relationshipThe 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 Model include relationship in use case diagramdiagram
Hoa Sen University 80
NextGen POS
Cashier
Customer
Handle CashPayment
Process Rental
Process Sale
Handle CheckPayment
Handle Returns
«include» «include»
«include»
«include» «include»«include»
«actor»Accounting
System
«actor»Credit
AuthorizationService
Manage Users
...
UML notation: the base use case points to the included use case
Handle CreditPayment
The extend relationshipThe 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 relationshipExample 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 Extend relationship in use case diagramdiagram
Hoa Sen University 83
Process Sale
Extension Points:Payment
VIP Customer
«extend»Payment, if Customer
presents a gift certificate
UML notation: 1. The extending use case points to the base use case.
2. The condition and extension point can be shown on the line.
Handle Gift Certificate Payment
Extend vs. include relationshipsExtend 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
Domain ModelDomain Model
Lecture 3Lecture 3
Hoa Sen University 85
AgendaAgenda
Recap Case Requirements Elaboration process Domain model
– Introduction and definition– How to create a domain model
Hoa Sen University 86
RecapRecap
Inception activities Different types of requirements Scenario & Use case Writing Use Cases Use Case Diagram Use case relationships
Hoa Sen University 87
Case requirementsCase 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 requirementsCase 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 requirementsCase 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 DevelopmentIncremental Development
Incremental development for the same use case across iteration
Hoa Sen University 91
1A use case or feature is often too complex to complete in one short iteration.
Therefore, different parts or scenarios must be allocated to different iterations.
Use CaseProcess Sale
2 3 . . .
Use CaseProcess Sale
Use CaseProcess Sale
Use CaseProcess Rentals
Feature: Logging
Process: inceptionProcess: 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 ElaborationProcess: 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 ElaborationProcess: 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 modelsDomain 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
ExampleExample
Hoa Sen University 96
Register
Item
Store
addressname
Sale
date time
Payment
amount
SalesLineItem
quantity
Stocked-in
*
Houses
1..*
Contained-in
1..*
Records-sale-of
0..1
Paid-by
1
1
1
1
1
1
0..1
1
Captured-on
conceptor domain object
association
attributes
Identifying a rich set of conceptual classes is at the heart of OO analysis
What is a domain modelWhat 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 dictionaryDomain 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 Domain model is not a picture of software objectssoftware objects
Domain model is a visualization of things in a real-world domain of interest
Not suitable in a domain model– Software artefacts– Responsibilities or
methodsHoa Sen University 99
Sale
dateTime
visualization of a real-world concept in the domain of interest
it is a not a picture of a software class
SalesDatabase software artifact; not part of domain modelavo
id
software class; not part of domain model
Sale
datetime
print()
avoid
What are conceptual classesWhat are conceptual classes
A conceptual class may be considered in terms of– Symbol – words or images
representing a conceptual class
– Intension – the definition of a conceptual class
– Extension – the set of examples to which the conceptual class applies
Hoa Sen University 100
Sale
datetime
concept's symbol
"A sale represents the event of a purchase transaction. It has a date and time."
concept's intension
sale-1
sale-3sale-2
sale-4
concept's extension
Domain model vs. Data modelDomain 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
MotivationMotivation Help to understand the key concepts in a business or problem
domain Lower representational gap with OO Modelling
Hoa Sen University 102
Payment
amount
Sale
datetime
Pays-for
Payment
amount: Money
getBalance(): Money
Sale
date: DatestartTime: Time
getTotal(): Money. . .
Pays-for
UP Domain ModelStakeholder's view of the noteworthy concepts in the domain.
UP Design ModelThe 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.
1 1
1 1
A Payment in the Domain Model is a concept, but a Payment in the Design Model is a software class. They are not the same thing, but the former inspired the naming and definition of the latter.
This reduces the representational gap.
This is one of the big ideas in object technology.
inspires objects
and names in
How to create a Domain ModelHow 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 classesFind 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 listUse 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 IdentificationNoun 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 eventExample: 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 Mapping parts of speech to object model componentsmodel 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 (Composition)
Has, consists of, includes
Modal verb Constraints Must be
Adjective attributes Attributes 3 years old
Hoa Sen University 108
Example: find and draw conceptual Example: find and draw conceptual classesclasses
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 modelInitial POS domain model
Hoa Sen University 110
StoreRegister SaleItem
CashPayment
SalesLineItem
Cashier Customer
ProductCatalog
ProductDescription
Ledger
Initial Domain model of MonopolyInitial Domain model of Monopolygame simulationgame simulation
Hoa Sen University 111
Agile modelling styleAgile 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?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 AttributesClass 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 ClassDescription 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?
Hoa Sen University 115
Item
descriptionpriceserial numberitemID
ProductDescription
descriptionpriceitemID
Item
serial number
Describes Better
Worse
1 *
Description classesDescription classes
When are description classes useful?– There needs to be a description
about an item or service, independent of the current existence of any examples of those items or services
– Deleting instances of things they describe results in a loss of information that needs to be maintained, but was incorrectly associated with the deleted things
– It reduces redundant or duplicated information
Hoa Sen University 116
Worse
Flight
datetime
FlightDescription
number
Airport
name
Describes-flights-to
Described-by
Flight
datenumbertime
Airport
name
Flies-to
Better
1*
1*
1
*
AssociationsAssociations
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.”
Hoa Sen University 117
SaleRegisterRecords-current
1 1
association
When to show associationWhen 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 implementationAssociations 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 NotationAssociation Notation
Hoa Sen University 120
SaleRegister Records-current 0..11
association name multiplicity
-"reading direction arrow"-it has no meaning except to indicate direction of reading the association label-often excluded
Naming associationNaming association
Name an association based on a ClassName-VerbPhrase-ClassName format
Eg.– Sales paid-by CashPayment
Bad alternative: Sales uses CashPayment
– Piece is-on SquareBad alternative: Piece has Square
Hoa Sen University 121
Applying UML: multiplicityApplying UML: multiplicity
Multiplicity defines how many instances of a class A can be associated with one instance of class B
Hoa Sen University 122
ItemStore Stocks
*
multiplicity of the role
1
Multiplicity valuesMultiplicity values
Multiplicity focus on the relationship at a particular moment, rather than over a span of time.
Eg. “In countries with monogamy laws, a person can be Married-to only one other person at any particular moment, even though over a span of time, that same person may be married to many persons.”
Hoa Sen University 123
zero or more; "many"
one or more
one to 40
exactly 5
T
T
T
T
*
1..*
1..40
5
T3, 5, 8
exactly 3, 5, or 8
Multiplicity valuesMultiplicity values
Hoa Sen University 124
ItemStore Stocks 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.
*
Multiple association between two Multiple association between two classesclasses
Hoa Sen University 125
Flight Airport
Flies-to
Flies-from
*
* 1
1
Find associationFind association
Use the common associations list– A is a physical part of B
Square – Board
– A is a logical part of BSalesLineItem – Sale
– A uses or submanages BCashier- Register
– A communicates with BCustomer – Cashier
– etc.
Hoa Sen University 126
POS partial domain modelPOS partial domain model
Hoa Sen University 127
Register
ItemStore
Sale
CashPayment
SalesLineItem
CashierCustomer
ProductCatalog
ProductDescription
Stocks
*
Houses
1..*
Used-by
*
Contains
1..*
Describes
*
Captured-on
Contained-in
1..*
Records-sale-of
0..1
Paid-by Is-for
Logs-completed
*
Works-on
1
1
1
1 1..*
1
1
1
1
1
1
1
0..1 1
1
Ledger
Records-accounts-
for
1
1
Monopoly partial domain modelMonopoly partial domain model
Hoa Sen University 128
AttributesAttributes
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 attributeStore needs a name and address.
Hoa Sen University 129
UML notationUML 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.
Hoa Sen University 130
Sale
- dateTime : Date- / total : Money
Private visibility attributes
Math
+ pi : Real = 3.14 {readOnly}
Public visibility readonly attribute with initialization
Person
firstNamemiddleName : [0..1]lastName
Optional value
Suitable attribute typesSuitable attribute types
Most attribute types should be what are often thought of as “primitive” data types
Relate conceptual classes with an association, not with an attribute
Hoa Sen University 131
Cashier
namecurrentRegister
Cashier
name
Register
number
Uses
Worse
Better
not a "data type" attribute
1 1
Flight
Flight
destinationWorse
BetterFlies-to Airport1 1
destination is a complex concept
Data types as attributesData 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.
Hoa Sen University 132
OK
OK
ProductDescription
ProductDescription
itemId : ItemID
1Store
Store
address : Address
11 1
ItemID
idmanufacturerCodecountryCode
Address
street1street2cityName...
Attributes are NOT foreign keysAttributes 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.
Hoa Sen University 133
Cashier
namecurrentRegisterNumber
Cashier
name
Register
number
Works-on
Worse
Better
a "simple" attribute, but being used as a foreign key to relate to another object
1 1
Modelling quantitiesModelling quantities
Hoa Sen University 134
Payment
amount : Number
Payment Quantity
amount : Number
Unit
...
Payment
amount : Quantity
Has-amount1*
Is-in1*
not useful
quantities are pure data values, so are suitable to show in attribute section better
Payment
amount : Money
variation: Money is a specialized Quantity whose unit is a currency
Iterative and evolutionary domain Iterative and evolutionary domain modelmodel
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 andContracts andUML interaction diagramsUML interaction diagrams
Lecture 4Lecture 4
Hoa Sen University 136
AgendaAgenda
System sequence diagram Operation Contract On to Object design
– Interaction diagramsSequence diagramsCommunication diagrams
Hoa Sen University 137
System Sequence DiagramSystem Sequence Diagram
Hoa Sen University 138
Operation: enterItem(…)
Post-conditions:- . . .
Operation Contracts
Sale
date. . .
SalesLineItem
quantity
1..*1 . . .
. . .
Domain Model
Use-Case Model
Design Model: Register
enterItem(itemID, quantity)
: ProductCatalog
spec = getProductSpec( itemID )
addLineItem( spec, quantity )
: Sale
Require-ments
Business Modeling
Design
Sample UP Artifact Relationships
: System
enterItem(id, quantity)
Use Case Text
System Sequence Diagrams
makeNewSale()
system events
Cashier
Process Sale
: Cashier
use case
names
system operations
Use Case Diagram
Vision
SupplementarySpecification
Glossaryparameters and
return value details
starting events to design for
Process Sale
1. Customer arrives ...2. Cashier makes new sale.3. ...
What is System Sequence DiagramWhat 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 diagramSystem sequence diagram
Hoa Sen University 140
enterItem(itemID, quantity)
:System: Cashier
endSale
makePayment(amount)
a UML loop interaction frame, with a boolean guard expression
external actor to system
Process Sale Scenario
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
a message with parameters
it is an abstraction representing the system event of entering the payment data by some mechanism
description, total
return value(s) associated with the previous message
an abstraction that ignores presentation and medium
the return line is optional if nothing is returned
total with taxes
change due, receipt
makeNewSale
[ more items ]loop
Use Cases and SSDsUse Cases and SSDs
Hoa Sen University 141
: Cashier :System
Simple cash-only Process Sale scenario:
1. Customer arrives at a POS checkout with goods and/or services to purchase.2. Cashier starts a new sale.3. Cashier enters item identifier.4. System records sale line item and presents item description, price, and running total. Cashier repeats steps 3-4 until indicates done.5. System presents total with taxes calculated.6. Cashier tells Customer the total, and asks for payment.7. Customer pays and System handles payment....
enterItem(itemID, quantity)
endSale
makePayment(amount)
description, total
total with taxes
change due, receipt
makeNewSale
[ more items ]loop
Process Sale Scenario
Choosing events and operation nameChoosing events and operation name
System events should be expressed at the abstract level of intention rather than in terms of the physical input device
Hoa Sen University 142
enterItem(itemID, quantity)
scan(itemID, quantity)
: Cashier
worse name
better name
:System
Iterative and Evolutionary SSDsIterative 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 ContractOperation Contract
Hoa Sen University 144
Operation: enterItem(…)
Post-conditions:- . . .
Operation Contracts
Sale
date. . .
SalesLineItem
quantity
1..*1 . . .
. . .
Domain Model
Use-Case Model
Design Model: Register
enterItem(itemID, quantity)
: ProductCatalog
spec = getProductSpec( itemID )
addLineItem( spec, quantity )
: Sale
Require-ments
Business Modeling
Design
Sample UP Artifact Relationships
: System
enterItem(id, quantity)
Use Case Text
System Sequence Diagrams
makeNewSale()
system events
Cashier
Process Sale
: Cashier
use case
names
system operations
Use Case Diagram
Vision
SupplementarySpecification
Glossary
starting events to design for, and more detailed requirements that must be satisfied by the software
Process Sale
1. Customer arrives ...2. ...3. Cashier enters item identifier.
the domain objects, attributes, and associations that undergo changes
requirements that must be satisfied by the software
ideas for the post-conditions
Example ContractExample 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 definitionContract 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 procedureContract 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 deletionAttribute change of valueAssociations (to be precise, UML links) formed and
brokenHoa Sen University 147
System operationsSystem operations
Hoa Sen University 148
: Cashier
enterItem(itemID, quantity)
endSale()
makePayment(amount)
description, total
total with taxes
change due, receipt
makeNewSale()
these input system events invoke system operations
the system event enterItem invokes a system operationcalled enterItem and so forth
this is the same as in object-oriented programming when we say the message foo invokes the method (handling operation) foo
[ more items ]loop
:System
Process Sale Scenario
Process Sale: makeNewSaleProcess 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 introductionObject 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 modellingStatic 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 diagramsInteraction 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 diagramSequence vs. Communication diagram
Sequence diagrams illustrate interactions in a kind of fence format– Easier to see the call
sequence– Large set of detailed notation
options
Communication diagrams illustrate interactions in a graph or network format– More space-efficient
Hoa Sen University 153
: A myB : B
doTwo
doOne
doThree
: A
myB : B
1: doTwo
2: doThree
doOne
Common notation: participants – Common notation: participants – lifeline boxlifeline box
Hoa Sen University 154
sales: ArrayList<Sale>
:Sale s1 : Sale
lifeline box representing an instance of an ArrayList class, parameterized (templatized) to hold Sale objects
lifeline box representing an unnamed instance of class Sale
lifeline box representing a named instance
sales[ i ] : Sale
lifeline box representing one instance of class Sale, selected from the salesArrayList <Sale> collection
x : List
«metaclass»Font
lifeline box representing the class Font, or more precisely, that Font is an instance of class Class – an instance of a metaclass
related example
List is an interface
in UML 1.x we could not use an interface here, but in UML 2, this (or an abstract class) is legal
Sequence diagram notationSequence diagram notation
Lifeline boxes and lifelines
Messages– Synchronous
message– Found message
Focus of control and execution specification bars
Hoa Sen University 155
: Register : Sale
doA
doB
doX
doC
doD
typical sychronous message shown with a filled-arrow line
a found message whose sender will not be specified
execution specification bar indicates focus of control
Sequence diagram notationSequence diagram notation
Illustrating reply or returns– Using the message syntaxreturnVar = message(parameter).
– Using a reply message line
Message to “self” or “this”public class Register{
public void doX(){
…
clear();
…
}
public void clear(){
}
}
Hoa Sen University 156
: Register : Sale
d1 = getDate
getDate
doX
aDate
: Register
doX
clear
Sequence diagram notationSequence diagram notation
Creation of instance– In implementation:
invoke the new operator and call the constructor
Object lifelines and object destruction– In language that
does not have garbage collection
Hoa Sen University 157
: Register : Sale
makePayment(cashTendered)
: Paymentcreate(cashTendered)
authorize
note that newly created objects are placed at their creation "height"
: Sale
: Paymentcreate(cashTendered)
...the «destroy» stereotyped message, with the large X and short lifeline indicates explicit object destruction
«destroy» X
Sequence diagram notationSequence diagram notation
Diagram frames in UML sequence diagrams– Support conditional and looping construct
Hoa Sen University 158
enterItem(itemID, quantity)
: B
endSale
a UML loop frame, with a boolean guard expression description, total
makeNewSale
[ more items ]loop
: A
Sequence diagram notationSequence diagram notation
Common frame operators
Hoa Sen University 159
Frame operator
Meaning
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
Sequence diagram notationSequence diagram notation
Conditional messagespublic class foo{
Bar bar = new Bar();
…
public void m1(){
bar.xx();
if (color.equals(“red”))
bar.calculate();
bar.yy();
}
}
UML1.x style
Hoa Sen University 160
calculate
: Bar
yy
xx
[ color = red ]opt
: Foo
[ color = red ] calculate
: Bar
yy
xx
: Foo
Mutually exclusive conditional messages
public class A{
B b = new B();
C c = new C();
public void doX(){
…
if (x < 10)
b.calculate();
else
c.calculate();
}
}
Hoa Sen University 161
: B: A
calculate
doX
: C
calculate
[ x < 10 ]alt
[ else ]
Sequence diagram notationSequence diagram notation
Iteration over a collection
Hoa Sen University 162
st = getSubtotal
lineItems[i] :SalesLineItem
t = getTotal
[ i < lineItems.size ]loop
: Sale This lifeline box represents one instance from a collection of many SalesLineItem objects.
lineItems[i] is the expression to select one element from the collection of many SalesLineItems; the ‘i” value refers to the same “i” in the guard 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
i++
Sequence diagram notationSequence 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);
}
}
}
Hoa Sen University 163
st = getSubtotal
lineItems[i] :SalesLineItem
t = getTotal
loop
: Sale
Sequence diagram notationSequence diagram notation
Nesting frames
Hoa Sen University 164
calculate
: Bar
xx
[ color = red ]opt
: Foo
loop(n)
Sequence diagram notationSequence 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 notationSequence diagram notation
Hoa Sen University 166
interaction occurrence
note it covers a set of lifelines
note that the sd frame it relates to has the same lifelines: B and C
doA
: A : B : C
doB
sd AuthenticateUser
refAuthenticateUserauthenticate(id)
doX
doM1
: B : C
authenticate(id)
doM2
refDoFoo
sd DoFoo
doX
: B : C
doY
doZ
Sequence diagram notationSequence diagram notation
Messages to classes to invoke static methodspublic class Foo{
public void doX(){
Locale[] locales = Calendar.getAvailableLocales();
..
}
}
Hoa Sen University 167
1: locs = getAvailableLocales: Foo
«metaclass»Calendar
doX
message to class, or a static method call
Sequence diagram notationSequence diagram notation
Polymorphic messages and cases
Hoa Sen University 168
:Register
authorize
doX
:Payment {abstract}
polymorphic messageobject in role of abstract superclass
:DebitPayment
doA
authorize
:Foo
stop at this point – don’t show any further details for this message
doB
:CreditPayment
doX
authorize
:Bar
Payment {abstract}
authorize() {abstract}...
CreditPayment
authorize()...
DebitPayment
authorize()...
Payment is an abstract superclass, with concrete subclasses that implement the polymorphic authorize operation
separate diagrams for each polymorphic concrete case
Sequence diagram notationSequence 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 notationCollaboration diagram notation
Links– A connection path between two
objects– Messages flow along link
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 messages in the current thread of control
– Many messages may flow along a same single link
Hoa Sen University 170
1: makePayment(cashTendered)2: foo
2.1: bar: Register :Sale
link line
1: msg22: msg33: msg4
3.1: msg5: Register :Sale
all messages flow on the same link
msg1
Collaboration diagram notation (cont)Collaboration diagram notation (cont)
Message to “self” or “this”
Creation of instances– Use a message named
create for this purpose
Create message may have parameters– Indicates a constructor
call with parameters in Java
Hoa Sen University 171
: Register
msg1
1: clear
1: create(cashier)
: Register :Sale
create message, with optional initializing parameters. This will normally be interpreted as a constructor call.
«create»1: make(cashier)
: Register :Sale
if an unobvious creation message name is used, the message may be stereotyped for clarity
1: create(cashier)
: Register :Sale {new}
Collaboration diagram notation (cont)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
Hoa Sen University 172
: Amsg1 : B1: msg2
: C
1.1: msg3not numbered
legal numbering
Collaboration diagram notation (cont)Collaboration diagram notation (cont)
Hoa Sen University 173
: Amsg1 : B1: msg2
: C
1.1: msg3
2.1: msg5
2: msg4
: D
2.2: msg6
first second
fourth
sixth
fifth
third
Collaboration diagram notation (cont)Collaboration diagram notation (cont)
Conditional messages– A conditional message is
shown by following a sequence number with a conditional clause in square brackets. The message is only sent if the clause evaluates to true
– Attach a letter to the sequence number to express mutually exclusive message
Hoa Sen University 174
1 [ color = red ] : calculate: Foo : Bar
message1
conditional message, with test
1a [test1] : msg2
: A : B
: C
1a.1: msg3
msg1
: D
1b [not test1] : msg4
1b.1: msg5
: E
2: msg6
unconditional after either msg2 or msg4 1a and 1b are mutually
exclusive conditional paths
Collaboration diagram notation (cont)Collaboration diagram notation (cont)
Iteration or Looping– Use a “*” to signify iteration
Hoa Sen University 175
1 * [ i = 1..n ]: num = nextInt: SimulatorrunSimulation : Random
iteration is indicated with a * and an optional iteration clause following the sequence number
Collaboration diagram notation (cont)Collaboration diagram notation (cont)
Iteration over a collection
Hoa Sen University 176
1 * [i = 1..n]: st = getSubtotal: Salet = getTotal
This lifeline box represents one instance from a collection of many SalesLineItem objects.
lineItems[i] is the expression to select one element from the collection of many SalesLineItems; the ‘i” value comes from the message clause.
lineItems[i]:SalesLineItem
this iteration and recurrence clause indicates we are looping across each element of the lineItems collection.
1 *: st = getSubtotal: Salet = getTotal lineItems[i]:SalesLineItem
Less precise, but usually good enough to imply iteration across the collection members
Collaboration diagram notation (cont)Collaboration diagram notation (cont)
Messages to a Class Object
Hoa Sen University 177
1: locs = getAvailableLocales: Foo
«metaclass»Calendar
doX
message to class, or a static method call
Collaboration diagram notation (cont)Collaboration diagram notation (cont)
Hoa Sen University 178
:Register authorizedoX :Payment {abstract}
polymorphic message
object in role of abstract superclass
:DebitPayment
authorize
:Foo
stop at this point – don’t show any further details for this message
separate diagrams for each polymorphic concrete case
doAdoB :CreditPayment
authorize
:BardoX
Polymorphic messages and cases
Collaboration diagram notation (cont)Collaboration diagram notation (cont)
Asynchronous and Synchronous calls
Hoa Sen University 179
3: runFinalization:ClockStarter System : Class
startClock
:Clock
1: create
2: run
asynchronous message
active object
Design class diagramDesign class diagram
Lecture 5Lecture 5
Hoa Sen University 180
AgendaAgenda
Notations Dependency Interaction and Class diagrams
Hoa Sen University 181
Design Class DiagramDesign Class Diagram
UML class diagram can be used in multiple perspectives.
Hoa Sen University 182
Register
...
endSale()enterItem(...)makePayment(...)
Sale
timeisComplete : Boolean/total
makeLineItem(...)
Register
...
Sale
timeisComplete : Boolean/total
Captures
1
11Domain Model
conceptual perspective
Design Model
DCD; software perspective
currentSale
Attributes in UMLAttributes in UML
Hoa Sen University 183
Register
...
...
Sale
...
...
1
Register
currentSale : Sale
...
Sale
...
...
using the attribute text notation to indicate Register has a reference to one Sale instance
using the association notation to indicate Register has a reference to one Sale instance
OBSERVE: this style visually emphasizes the connection between these classes
currentSale
Register
currentSale : Sale
...
Sale
...
...
1thorough and unambiguous, but some people dislike the possible redundancy
currentSale
Attributes in UMLAttributes 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. DCDDomain Model vs. DCD
Hoa Sen University 185
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
id: Int
...
Sale
time: DateTime
...
1
currentSale
Register
id : Int
Sale
time : DateTime
Captures-current-sale1 1UP Domain Modelconceptual perspective
UP Design ModelDCD
software perspective
Collection attributesCollection attributes
public class Sale{
private List <SalesLineItem> lineItems = new ArrayList<SalesLineItem>();
}
}
Hoa Sen University 186
notice that an association end can optionally also have a property string such as {ordered, List}
Sale
time: DateTime
...
SalesLineItem
...
...
1..*lineItems
{ordered, List}
Sale
time: DateTimelineItems : SalesLineItem [1..*] orlineItems : SalesLineItem [1..*] {ordered}
...
SalesLineItem
...
...
Two ways to show a collection attribute
MethodsMethods
Method signature is shown in the third compartment of UML class box
Should correspond with the messages in interaction diagram
Hoa Sen University 187
Register
...
endSale()enterItem(id, qty)makeNewSale()makePayment(cashTendered)
«method»// pseudo-code or a specific language is OKpublic void enterItem( id, qty ){ ProductDescription desc = catalog.getProductDescription(id); sale.makeLineItem(desc, qty);}
Note Symbol & Operation issuesNote 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
KeywordsKeywords
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
Hoa Sen University 189
Keyword Meaning Example usage
{abstract} Classifier is an abstract class
In class diagram, above classifier name
«interface» Classifier is an interface In class diagram, above classifier name
Generalization, abstract class, Generalization, abstract class, abstract operationabstract 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
DependencyDependency
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 dependencyWhen 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 exampleDependency example
public class Sale {
public void updatePriceFor( ProductionDescription desc) {
Money basePrice = desc.getPrice();
//...
}
}
Hoa Sen University 193
SalesLineItem
...
...
ProductDescription
...
...
1..*lineItems
Sale
...
updatePriceFor( ProductDescription )...
the Sale has parameter visibility to a ProductDescription, and thus some kind of dependency
Dependency example (cont)Dependency example (cont)
public class Foo{
public void doX(){
System.runFinalization();
//..
}
}
Hoa Sen University 194
System
...
runFinalization()...
Foo
...
doX()...
the doX method invokes the runFinalization static method, and thus has a dependency on the System class
Dependency labelsDependency 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
InterfaceInterface
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
ConstraintsConstraints
Hoa Sen University 197
Stack
size : Integer { size >= 0 }
push( element )pop() : Object
three ways to show UML constraints
{ post condition: new size = old size + 1 }
{ post condition: new size = old size – 1 }
Template ClassesTemplate Classes
public class Board{
private List <Square> squares = new ArrayList<Square>();
//..
}
Hoa Sen University 198
«interface»List
clear()...
Kparameterized or template interfaces and classes
K is a template parameter
anonymous class with template binding complete
Board
squares : List<K Square> orsquares : List<Square>...
ArrayList<T Square>
clear()...
the attribute type may be expressed in official UML, with the template binding syntax requiring an arrow orin another language, such as Java
ArrayList
elements : T[*]...
clear()...
T
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., ‘=’
User-defined compartmentsUser-defined compartments
Hoa Sen University 199
DataAccessObject
id : Int...
doX()...
exceptions thrownDatabaseExceptionIOException
responsibilitiesserialize and write objectsread and deserialize objects...
Interaction and Class DiagramsInteraction and Class Diagrams
Hoa Sen University 200
: Register : Sale
makePayment(cashTendered)
makePayment(cashTendered)
Register
...
makePayment(…)...
Sale
...
makePayment(…)...
1
currentSale
messages in interaction diagrams indicate operations in the class diagrams classes
identified in the interaction diagrams are declared in the class diagrams
Object DesignObject Design
Lecture 6Lecture 6
Hoa Sen University 201
AgendaAgenda
Object design basics Monopoly game design and GRASP
principles introduction GRASP principles in POS projects
Hoa Sen University 202
Object DesignObject 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: inputObject 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 outputObject Design: activities and output
Design activities– Coding immediately
Using test-driven development
– Short UML modellingApply 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
ResponsibilitiesResponsibilities
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 responsibilitiesExamples 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 responsibilitiesDomain 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 UMLResponsibilities and UML
Hoa Sen University 209
: Sale
makePayment(cashTendered)
: Paymentcreate(cashTendered)
abstract, implies Sale objects have a responsibility to create Payments
GRASP principlesGRASP 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: problemCreator: problem
Problem– Who creates the Square object
Start point: domain model
Hoa Sen University 211
Creator: principleCreator: 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 trueB “contains” AB records AB closely uses AB has the Initializing data for A
Hoa Sen University 212
Creator: SolutionCreator: Solution
Hoa Sen University 213
Information ExpertInformation 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: principleInformation 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 couplingLow 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
CouplingCoupling
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 designExample of poor design
Hoa Sen University 218
ControllerController
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
ExampleExample
Hoa Sen University 220
ExampleExample
Hoa Sen University 221
ExampleExample
Hoa Sen University 222
High cohesionHigh 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
CohesionCohesion
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
ExampleExample
Hoa Sen University 225
Applying GRASP to POS designApplying GRASP to POS design
Creator– Example: Who
should be responsible for creating a SalesLineItem instance
– Solution: Sale contains many SalesLineItem objects.
Hoa Sen University 226
Sale
time
SalesLineItem
quantity
ProductDescription
descriptionpriceitemID
Described-by*
Contains
1..*
1
1
: Register : Sale
makeLineItem(quantity)
: SalesLineItemcreate(quantity)
GRASP in POS projectGRASP in POS project
Information Expert Example
– Who should be responsible for knowing the grand total of a sale
– What information do we need to compute the grand total SalesLineItem
Hoa Sen University 227
Sale
time
SalesLineItem
quantity
ProductDescription
descriptionpriceitemID
Described-by*
Contains
1..*
1
1
Create diagrams in parallelCreate diagrams in parallel
Hoa Sen University 228
Sale
time...
getTotal()
:Salet = getTotal
New method
The new responsibility is conveyed by an operation in aninteraction diagram. A new method is created in the designclass to express this.
Create diagram in parallelCreate diagram in parallel
Responsibility for each subtotal is assigned to the SalesLineItem
Hoa Sen University 229
Sale
time...
getTotal()
SalesLineItem
quantity
getSubtotal()New method
1 *: st = getSubtotal: Salet = getTotal lineItems[ i ] : SalesLineItem
this notation will imply we are iterating over all elements of a collection
Sale
time...
getTotal()
SalesLineItem
quantity
getSubtotal()
ProductDescription
descriptionpriceitemID
getPrice()New method
:ProductDescription
1.1: p := getPrice()
1 *: st = getSubtotal: Salet = getTotal lineItems[ i ] :SalesLineItem
Create diagrams in parallelCreate diagrams in parallel
Responsibility for each item price is assigned to the ProductSpecification
Hoa Sen University 230
GRASP in POS projectsGRASP in POS projects
How should we assignment responsibilities of creating Payment instance and associate it with the Sale.
Hoa Sen University 231
OptionsOptions
Hoa Sen University 232
: Register p : Payment
:Sale
makePayment() 1: create()
2: addPayment(p)
: Register :Sale
:Payment
makePayment() 1: makePayment()
1.1. create()
GRASP in POS projectGRASP in POS project
Hoa Sen University 233
actionPerformed( actionEvent )
:Register
: Cashier
:SaleJFrame
presses button
1: enterItem(itemID, qty)
:Sale1.1: makeLineItem(itemID, qty)
UI Layer
Domain Layer
system operation message
controller
Controller ChoicesController Choices
Represents the overall “system”, “root object”, device or subsystem– Register
Represents a receiver or handler of all system events of a user case scenario
Hoa Sen University 234
:RegisterenterItem(id, quantity)
:ProcessSaleHandlerenterItem(id, quantity)
Allocate system operationsAllocate system operations
Hoa Sen University 235
Register
...
endSale()enterItem()makeNewSale()makePayment()
makeNewReturn()enterReturnItem(). . .
System
endSale()enterItem()makeNewSale()makePayment()
makeNewReturn()enterReturnItem(). . .
system operations discovered during system behavior analysis
allocation of system operations during design, using one facade controller
ProcessSaleHandler
...
endSale()enterItem()makeNewSale()makePayment()
System
endSale()enterItem()makeNewSale()makePayment()
enterReturnItem()makeNewReturn(). . .
allocation of system operations during design, using several use case controllers
HandleReturnsHandler
...
enterReturnItem()makeNewReturn(). . .
Choosing a ControllerChoosing 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 toDesirable coupling of UI layer todomain layerdomain layer
Hoa Sen University 237
actionPerformed( actionEvent )
:Register
: Cashier
:SaleJFrame
presses button
1: enterItem(itemID, qty)
:Sale1.1: makeLineItem(itemID, qty)
UI Layer
Domain Layer
system operation message
controller
Less desirable couplingLess desirable coupling
Hoa Sen University 238
Cashier
:SaleJFrame
actionPerformed( actionEvent )
:Sale1: makeLineItem(itemID, qty)
UI Layer
Domain Layer
It is undesirable for an interfacelayer object such as a window to get involved in deciding how to handle domain processes.
Business logic is embedded in the presentation layer, which is not useful.
SaleJFrame should not send this message.
presses button
High cohesionHigh cohesion
Reconsider the problem presented and solved by “Low coupling” principle
Hoa Sen University 239
: Register : Sale
addPayment( p )
p : Paymentcreate()makePayment()
From previous practice, Register is mainly responsible for handling Systemoperations such as enterItem, endSale, and so on; The responsibility of creatingpayment instance is not cohesive with other responsibilities
Desirable solutionDesirable solution
Hoa Sen University 240
: Register : Sale
makePayment()
: Paymentcreate()
makePayment()
Use case realizationUse case realization
Lecture 7Lecture 7
Hoa Sen University 241
AgendaAgenda
Recap Use Case Realization with GRASP
– POS project– Monopoly Game project
Designing for visibility
Hoa Sen University 242
RecapRecap
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 createdSome action needs to be taken
Hoa Sen University 243
Use-Case RealizationUse-Case Realization
“…describes how a particular use case is realized within the design model, in terms of collaborating objects” [RUP]
Individual scenarios are realized
Hoa Sen University 244
Use case -> System events -> System sequence diagram ->System operation contracts -> Interaction diagrams -> Design classes
System operationSystem operation
Hoa Sen University 245
:RegisterenterItem
:RegisterendSale
:RegistermakePayment
1: ???
1: ???
1: ???
:RegistermakeNewSale 1: ???
makeNewSale, etc., are the system operations from the SSD
each major interaction diagram starts with a system operation going into a domain layer controller object, such as Register
DOMAIN LAYERUI LAYER
Window objects or
GUI widget objectsor
Web control objects
. . .
The system operations in the SSD are used as the start messages into the domain layerIf communication diagrams are used, one per system operationSame for sequence diagram
One diagram per system operationOne diagram per system operation
Hoa Sen University 246
: Register
: Sale
makeNewSalecreate
: Register
enterItem(...)
: ProductCatalog
desc = getProductDesc( itemID )
. . .
UI LAYER
Window objects or
GUI widget objectsor
Web control objects
. . .
DOMAIN LAYER
Design makeNewSaleDesign 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 makeNewSaleDesign makeNewSale
Hoa Sen University 248
:Register
makeNewSale
:Salecreate
Register creates a Sale by Creator
create lineItems :List<SalesLineItem>
by Creator, Sale creates an empty collection (such as a List) which will eventually hold SalesLineItem instances
by Creator and Controller
this execution specification is implied to be within the constructor of the Sale instance
Design: enterItemDesign: 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 enterItemDesign 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 enterItemDesign enterItem
Hoa Sen University 251
2: makeLineItem(desc, qty)enterItem(id, qty)
1: desc = getProductDesc(id) 2.1: create(desc, qty)
1.1: desc = get(id)
:Register :Sale
:ProductCatalog
sl: SalesLineItem
lineItems : List<SalesLineItem>
: Map<ProductDescription>
2.2: add(sl)
by Expert
by Controllerby Creator
add the newly created SalesLineItem instance to the List
Partial Design Class DiagramPartial Design Class Diagram
Hoa Sen University 252
SalesLineItem
quantity : Integer
...
ProductCatalog
...
getProductDesc(...)
ProductDescription
description : Textprice : MoneyitemID: ItemID
...
1..*
1..*
Register
...
enterItem(...)...
Sale
isComplete : Booleantime : DateTime
makeLineItem(...)...1
1
1
catalog
currentSale
descriptions{Map}
lineItems{ordered}
description
Design endSaleDesign endSale
Hoa Sen University 253
:Saletot = getTotal 1 *[ i = 1..n]: st = getSubtotal
:ProductDescription
1.1: pr = getPrice
lineItems[ i ] :SalesLineItem
«method»public void getTotal(){ int tot = 0; for each SalesLineItem, sli tot = tot + sli.getSubtotal(); return tot}
Design makePaymentDesign 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 makePaymentDesign makePayment
Creating payment
Hoa Sen University 255
1: makePayment(cashTendered)
1.1: create(cashTendered)
:Register :Sale
:Payment
makePayment(cashTendered)
by Controller by Creator and Low Coupling
Design makePaymentDesign makePayment
Logging a sale
Hoa Sen University 256
Store
...
addSale(s : Sale)...
SalesLedger
...
addSale(s : Sale)...
Store is responsible for knowing and adding completed Sales.
Acceptable in early development cycles if the Store has few responsibilities.
SalesLedger is responsible for knowing and adding completed Sales.
Suitable when the design grows and the Store becomes uncohesive.
Sale
...
...
Sale
...
...
Logs-completed Logs-completed
* *
1 1
Design makePaymentDesign makePayment
Hoa Sen University 257
1: makePayment(cashTendered)
1.1: create(cashTendered)
:Register s :Sale
:Payment
makePayment(cashTendered)
:Store
2: addSale(s)
completedSales: List<Sale>
2.1: add(s)
by Expert
note that the Sale instance is named's' so that it can be referenced as a parameter in messages 2 and 2.1
Design makePaymentDesign 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 designgetBalance design
Hoa Sen University 259
s :Sale pmt: Payment1: amt = getAmountbal = getBalance
2: t = getTotal
{ bal = pmt.amount - s.total }
Object Design: startUpObject 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 ObjectCreate 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()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()Designing Store.create()
Hoa Sen University 263
:Store :Register
pc:ProductCatalog
create 2: create(pc)
1: create
1.2: loadProdSpecs()
descriptions:Map<ProductDescription>
1.1: create
1.2.2*: put(id, pd)
1.2.1*: create(id, price, description)
pd:ProductDescriptionthe * in sequence number indicates the
message occurs in a repeating section
pass a reference to the ProductCatalog to the Register, so that it has permanent visibility to it
by Creatorcreate an empty collection object
Monopoly game projectMonopoly game project
Two system operations in the first iteration– Initialize
Ignore at this state
– Play gameMain focus
Hoa Sen University 264
Design playGameDesign 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 scenarioPlayGameHandler?
Hoa Sen University 265
Game-Loop algorithmGame-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 Who is responsible for controlling the game loopthe game loop
Information needed Who has this information
The current round count No object has it yet, assigning this to theMonopolyGame object is justifiable
All players MonopolyGame object
Hoa Sen University 267
Who takes a turn?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
Hoa Sen University 268
Information Needed Who has the information
Current location of the player Player
Two die objects MonopolyGame
All the squares Board
Partial design diagramsPartial design diagrams
Hoa Sen University 269
Taking a turn refineTaking 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 turnTaking a turn
Hoa Sen University 271
Command-Query Separation PrincipleCommand-Query Separation Principle
Style 1#public void roll(){
faceValue = //random num generation
}
public int getFaceValue(){
return faceValue;
}
Style 2#public int roll(){
faceValue = //random num generation
return faceValue;
}
Every method should either be:– A command method that
performs an action often has side effects such as changing the state of objects and is void.
– A query that returns data to the caller and has no side effects – it should not permanently change the state of any objects.
But a method should not be both
Hoa Sen University 272
Static design for playGameStatic design for playGame
Hoa Sen University 273
Initialization and the start up useInitialization and the start up usecasecase
Hoa Sen University 274
Visibility between objectsVisibility between objects
Hoa Sen University 275
: RegisterenterItem
(itemID, quantity)
: ProductCatalog
desc = getProductDesc( itemID )
public void enterItem( itemID, qty ){ ... desc = catalog.getProductDesc(itemID) ...}
class Register{ ... private ProductCatalog catalog; ...}
What is visibilityWhat 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 visibilityB is in some way globally visible
Hoa Sen University 276
Attribute VisibilityAttribute Visibility
Hoa Sen University 277
: RegisterenterItem
(itemID, quantity)
: ProductCatalog
desc = getProductDesc( itemID )
public void enterItem(itemID, qty){ ... desc = catalog.getProductDesc(itemID) ...}
class Register{ ... private ProductCatalog catalog; ...}
Parameter VisibilityParameter Visibility
Hoa Sen University 278
2: makeLineItem(desc, qty)enterItem(id, qty)
1: desc = getProductDesc(id)
2.1: create(desc, qty)
:Register :Sale
:ProductCatalog
sl : SalesLineItemmakeLineItem(ProductDescription desc, int qty){ ... sl = new SalesLineItem(desc, qty); ...}
Parameter to attribute visibilityParameter to attribute visibility
Hoa Sen University 279
2: makeLineItem(desc, qty)enterItem(id, qty)
2: desc = getProductDesc(id)
2.1: create(desc, qty)
:Register :Sale
:ProductCatalog
sl : SalesLineItem
// initializing method (e.g., a Java constructor)SalesLineItem(ProductDescription desc, int qty){ ...description = desc; // parameter to attribute visibility...}
Local visibilityLocal 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
Hoa Sen University 280
: RegisterenterItem
(itemID, quantity)
: ProductCatalog
desc = getProductDesc( itemID )
enterItem(id, qty){ ...// local visibility via assignment of returning objectProductDescription desc = catalog.getProductDes(id);...}
Global visibilityGlobal 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