Object-Oriented Analysis and Design Rectangle 8
with Patterns, Process, and the UML Introduction
Introduction Welcome! Introductions – Course leader: Dr. Trần Vũ Bình – Participants: MSc. Nguyễn Ngọc Tú (Lecturer) MSc. Phạm Thị Thu Trang (Lecturer) Hồ Thuỵ Hương Thuỷ (Tutor) Nguyễn Bá Trung (Tutor)
Prerequisites: Object-Oriented Programming Logistics
Overview and Objectives Learn how to “think in objects” Requirements and analysis of the problem domain Design of a solution – – – –
Assign responsibilities to objects Design patterns Architectural issues Java and/or C++ issues
Unified Process UML Practice!
Assessment components
Hoa Sen University
4
Team work Software development is a team-oriented activity… Two assignments will work around the same project You need to work in the same team for both assignments Preferred team size: 2-3 students You can do it by yourself Form your team as early as possible Hoa Sen University
5
Team Project – Collaborative Tagging System Your client: – Charities Inc. a search engine company
Your goal: – Design a system to allow users to upload and collaboratively tag web contents: article or image. Manage registered users Manage contents and their tags Produce summaries upon request
Hoa Sen University
6
Project Task Assignment 1 – Prepare requirement document – Write use cases – Develop Domain Model
Assignment 2 – Write Design Document – Implement the system (desktop version) – System Demo
Hoa Sen University
7
Software Microsoft Visio – Licensed software – Installed on the lab PC
Hoa Sen University
8
Rectangle 8
What is OOAD?
Lecture 1
Hoa Sen University
9
Today’s lecture topic
What’s OOAD? Functional decomposition and its problem What’s UML? Software Development Process
Hoa Sen University
10
What is Analysis and Design Analysis emphasizes an investigation of the problem and requirements rather than how a solution is defined Design emphasizes a conceptual solution that system fulfils the requirements rather than its implementation
Hoa Sen University
11
What is O-O A&D? The essence of O-O A&D is to consider a problem domain and logical solution from the perspective of objects (things, concepts, or entities) O-O Analysis emphasizes finding and describing the objects – or concepts- in the problem domain O-O Design emphasizes defining logical software objects (things, concepts, or entities) that have attributes and methods Hoa Sen University
12
Object vs. Function Oriented Analysis Library Information System
OOA&D Decompose by objects and concepts
Catalogue
Librarian
Book
Library
Structured A&D Decompose by functions and processes
Hoa Sen University
13
Functional Decomposition A very simple development case – You are asked to write code to access a list of shapes that were stored in a database then display them
What steps we need to achieve this? 1.Locate the list of shapes in the database 2.Open up the list of shapes 3.Sort the list according to some order 4.Display the individual shapes on the monitor Hoa Sen University
14
Functional Decomposition We might breakdown some step further – Identify the type of shapes – Get the location of the shape – Call the appropriate function that will display the shape, giving it the shape’s location
This is called functional decomposition because the analyst breaks down (decomposes) the problem into the functional steps that compose it. Hoa Sen University
15
How do people do things Case: – You are an instructor at a seminar. People in your seminar have another class to attend following yours, but don’t know where it is located. One of your responsibilities is to make sure everyone knows how to get to the next class.
Hoa Sen University
16
A “software like” option Steps:
Procedures needed:
– Get list of people in the class – 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
– 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” option What’s the alternatives? – Post a directions to go from this classroom to the other classrooms and tell everyone in the class “ I have posted the locations of the other classes following this in the back of the room, as well as the locations of the other classrooms. Please use them to go to your next classroom. ”
– Assume everyone knows what his or her next class is Hoa Sen University
18
Difference? Option 1: giving explicit directions to everyone – pay attention to lots of details. You are responsible for everything Option 2: giving general instructions and then expect each person will figure out how to do the task individually – Two kinds of objects Instructor: responsible for posting the instruction Students: knowing their own next classes, able to follow the instruction
Key point: Shift of responsibility! Hoa Sen University
19
Dealing with changing requirements Impact – What if you need to distinguish postgraduate students from undergraduate students? – Option 1: change the control program a lot – Option 2: add an additional routine for graduate students to follow
The second case can minimize changes
Hoa Sen University
20
Dealing with changing requirements What makes it happen? – The people are responsible for their own behaviour – The control program can talk to different types of people as if they were exactly the same – The control program does not need to know about any special steps that students might need to take when moving from class to class
Hoa Sen University
21
Key Steps in OOAD [1]
Use Case: a textual description or “story” describing the system Play a Dice Game: Player requests to roll the dice. System presents results: If the dice face value totals seven, player wins; otherwise, player loses.
Hoa Sen University
22
Key steps in OOAD [2]
a domain model that shows the noteworthy domain concepts or objects, attributes, and associations Player
1
Rolls
Die
2
name
faceValue 1
2 Plays
1 DiceGame
1
Includes Hoa Sen University
23
Key steps in OOAD [3]
Interaction Diagram: shows the flow of messages between software objects (method invocation) :DiceGame
die1 : Die
die2 : Die
play() roll() fv1 := getFaceValue() roll() fv2 := getFaceValue() Hoa Sen University
24
Key steps in OOAD [4]
Class Model: shows attributes, methods and associations for software (solution) objects (not domain objects!) DiceGame die1 : Die die2 : Die
Die 1
2
faceValue : int getFaceValue() : int roll()
play() Hoa Sen University
25
Iterative and Evolutionary Development Iterative development – Development is organized into a series of short, fixed-length mini-projects called iterations. – the outcome of each is a tested, integrated, and executable partial system. – Known as iterative and incremental development
Hoa Sen University
26
Iterative and evolutionary development Requirements
Requirements Design Implementation & Test & Integration & More Design Final Integration & System Test
3 weeks (for example)
Time
Design Implementation & Test & Integration & More Design
Feedback from iteration N leads to refinement and adaptation of the requirements and design in iteration N+1.
Final Integration & System Test
Iterations are fixed in length, or timeboxed.
Hoa Sen University
The system grows incrementally.
27
Handle change on iterative project 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
Hoa Sen University
28
How long should an iteration be? Most iterative methods recommend an iteration length between two and six weeks. Iteration are timeboxed, or fixed in length Date slippage is illegal If it seems difficult to meet the deadline, the recommended response is to de-scope – remove tasks or requirements from the iteration, and include them in a future iteration Hoa Sen University
29
How to do Iterative and Evolutionary Analysis and Design? 1
2
3
4
5
...
20
software
requirements
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.
software
Imagine this will ultimately be a 20 iteration project.
requirements
requirements workshops
90%
90%
50% 30%
20%
5%
2%
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
a 3week iteration
week 1 M
kickoff meeting clarifying iteration goals with the team. 1 hour
20%
10%
8%
T
team agile modeling & design, UML whiteboard sketching. 5 hours
week 2 W
Th
start coding & testing
F
M
T
week 3 W
descope iteration goals if too much work
Most OOA/D and applying UML during this period
Hoa Sen University
Th
F
M
final checkin and code freeze for the iteration baseline
T
W
Th
demo and 2day requirements workshop
F
next iteration planning meeting; 2 hours
Usecase modeling during the workshop
30
Agile Methods and attitudes Agile development methods usually apply timeboxed iterative and evolutionary development, employ adaptive planning, promote incremental delivery and include other values and practices that encourage agility – rapid, and flexible response to change. Example – programming in pairs – test-driven development Hoa Sen University
31
Agile Modelling Adopting an agile method does not mean avoiding any modelling The purpose of modelling and models is primarily to support understanding and communication, not documentation Don’t model or apply the UML to all or most of the software design Use the simplest tool possible Hoa Sen University
32
Agile modelling (cont) Don’t model alone Create models in parallel Use “good enough” simple notation while sketching with a pen on paper Know that all models will be inaccurate Developers themselves should do the OO design modelling, for themselves, not to create diagrams that are given to other programmers to implement. Hoa Sen University
33
Layers and textbook case study minor focus
User Interface
application logic layer
other layers or components
explore how to connect to other layers
Sale
Logging ...
Payment
Database Access ...
Hoa Sen University
primary focus of case studies explore how to design objects
secondary focus
34
Case study strategy
Iteration 1 Iteration 2
Introduces just those analysis and design Additional analysis and skills related to design skills introduced. iteration one.
Hoa Sen University
Iteration 3 Likewise.
35
Cases Case one: The NextGen POS system – A POS system is a computerized application used (in part) to record sales and handle payments – Hardware: computer, bar code scanner – Software – Interfaces to service applications: tax calculator, inventory control
Case Two: The Monopoly Game System Hoa Sen University
36
Rectangle 8
Inception
Lecture 2
Hoa Sen University
37
Agenda
Recap Inception overview Evolutionary Requirements Use cases Other requirements Assignment 1 instruction
Hoa Sen University
38
What we learned last week Difference between analysis and design Different focuses of functional decomposition and object-oriented approach Benefit of OO approach UML Iterative development Agile modelling Hoa Sen University
39
Inception Questions What is the vision and the business case for this project? Feasible? Buy and/or build? Rough estimate of cost: $10K, $100K, $1M, … Should we proceed or stop? Hoa Sen University
40
Goals of Inception “…to do just enough investigation to form a rational, justifiable opinion of the overall purpose and feasibility of the potential new system.” Envision the product scope, vision and business case Do the stakeholders have basic agreement on the vision of the project? Is it worth investigating seriously? Hoa Sen University
41
Artefacts in Inception Artefacts
Comments
Vision and Business 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-ofconcepts
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 if
It takes more than a few weeks You attempt to define most requirements Estimates are expected to be reliable You define a concrete architecture No business case or vision document Too little or too much use case modelling
Hoa Sen University
43
Hoa Sen University
44
Understanding Requirements “Capabilities and conditions to which the system and project must conform” [Jacobson et al., 1999] Challenges: {find, communicate, record, manage} the requirements Requirements always change, so effective management is critical
Hoa Sen University
45
Evolutionary vs. Waterfall requirements UP embraces change in requirements as a fundamental driver on projects Start production-quality programming and testing long before most of the requirements have been analysed or specified.
Hoa Sen University
46
The FURPS+ Model Functional – features, capabilities, security Usability – human factors, help, documentation Reliability – failure frequency, recoverability Performance – response times, throughput, accuracy, availability, resource utilization Supportability – adaptability, maintainability, internationalization, configurability
Hoa Sen University
47
The FURPS+ Model Implementation – resource limitations, languages/tools, hardware Interface – with legacy systems Operations – sysop management Packaging – delivery, installation Legal – licensing, etc. Use FURPS+ as a global checklist when identifying requirements for a system you are designing
Hoa Sen University
48
Other Terminology Quality Attributes, or “-ilities” – Usability, reliability, supportability, performance (non-functional)
Functional vs. Non-Functional – Behavioural features vs. everything else
The quality attributes have a strong influence on the architecture of a system
Hoa Sen University
49
Document Requirements Primarily, in the use case model – functional requirements
Also, Supplementary Specifications – other requirements
Glossary – noteworthy terms Vision – high-level requirements Business Rules – Requirements or policies that transcend one software project – many applications in the same domain may need to conform to them Hoa Sen University
50
The Use Case Model “Writing Requirements in Context” Identify user goals, corresponding system functions / business processes Brief, casual, and “fully-dressed” formats Iterative refinement of use cases
Hoa Sen University
51
Stories Using a system to meet goals E.g. brief format – Process Sale: A customer arrives at a checkout with items to purchase. The cashier uses the POS system to record each purchased item. The system presents a running total and lineitem details. The customer enters payment information, which the system validates and records. The system updates inventory. The customer receives a Receipt from the system and then leaves with the items.
Usually, writing the stories is more important than diagramming a use case model in UML
Hoa Sen University
52
Definitions Actor: something with a behaviour; person, system, organization Scenario: specific sequence of actions and interactions between actor(s) and system (= one story; success or failure) Use Case: collection of related success and failure scenarios describing the actors attempts to support a specific goal
Hoa Sen University
53
Examples Handle Returns – Main Success Scenario: A customer arrives at a checkout with items to return. The cashier uses the POS system to record each returned item… – Alternate Scenarios: If they paid by credit, and the reimbursement transaction to their credit account is rejected, inform the customer and pay them with cash. If the item identifier is not found in the system, notify the cashier and suggest manual entry of the identifier code If the system detects failure to communicate with the external accounting system… (etc.)
Hoa Sen University
54
Why use cases? A key attitude in use case work is to focus on the question ‘How can using the system provide observable value to the user, or fulfil their goals? rather than merely thinking of requirements in terms of a list of features or functions Focus on business process, not technology features
Hoa Sen University
55
Common use case formats Brief: one-paragraph summary, main success scenario – When? During early requirements analysis
Casual: multiple, informal paragraphs covering many scenarios – When? Also early requirements analysis
Fully-Dressed: all steps and variations written in detail with supporting sections – See http://alistair.cockburn.us/usecases/usecases.html – When? Before each elaboration starts, do it for a portion of use cases selected for the following elaboration Hoa Sen University
56
NextGen POS example A fully dressed example – – – – – – – – – – –
Use case name Scope & level Primary Actor Stakeholders and Interests Preconditions Success Guarantee Main Success scenario Extensions Special Requirements Technology and Data Variations List Miscellaneous Hoa Sen University
57
Details ... Use case name – Start with a verb – “Process Sale”
Scope – The system under design – “NextGen POS application”
Level – User-goal or subfunction – “User-goal”
Primary actor – Calls on the system to delivery the service – “Cashier”
Stakeholders and Interests – Who care about this use case and what do they want? – “Government Tax Agencies: Want to collect tax from every sale” Hoa Sen University
58
Details… Preconditions – What must be true on start, and worth telling the reader – “Cashier is identified and authenticated”
Success Guarantee – What must be true on successful completions, and worth telling the reader – “Sales is saved. Tax is correctly calculated…”
Hoa Sen University
59
Details… Main Success Scenario (or Basic flow) – A typical, unconditional happy path scenario of success – Record steps: An interaction between actors A validation (usually by the system) A state change by the system
– E.g. 1.Customer arrives at a POS checkout 2.Cashiers starts a new sale 3.Cashier enters item identifier 4.System record sales line item…
– Cashier repeats steps 3-4 until indicates done. 1.System presents total with taxes calculated
Hoa Sen University
60
Details… Extensions ( or Alternate Flows ) – Alternate scenarios of success or failure
Scenario branches (success/failure) Longer/more complex than basic flow Branches indicated by letter following basic flow step number, e.g. “3a” Two parts: condition, handling
– E.g. Extensions: 3a. Invalid identifier 1.
System signals error and reject entry
– When possible write the condition as something that can be detected 5a: System can not communication with external tax calculation system 5a: External tax calculation system not working
– If condition can arise within a range of steps 3-6a: customer asks Cashier to remove an item from the purchase 1. 2.
Cashier enters the item identifier for removal from the sale System displays updated running total.
– At the end of extension handling, by default the scenario merges back with the main success scenario, unless the extension indicates otherwise Hoa Sen University
61
Details… Special Requirements – Related non-functional requirements Touch screen UI on a large flat panel monitor Language internationalization on the text displayed
Technology and Data Variation List – Varying I/O methods and data formats (nonfunctional constraints expressed by the stakeholder) Item identifier entered by laser scanner or keyboard Credit account information entered by card reader or keyboard Hoa Sen University
62
Guidelines 1 Write in an essential UI-Free Style – The narrative is expressed at the level of the user’s intentions and system’s responsibilities – Essential Style 1. Administrator identified self. 2. System authenticates identity. 3. …
Concrete Style – Administrator enters ID and passwd in dialog box – System authenticates Administrator. – System displays the “edit users” window Hoa Sen University
63
Guideline 2 Write Black-Box use cases – Focus on “what”, not “how” – Good: The system records the sale – Bad: The system writes the sale to a database – Worse: The system generates a SQL INSERT statement…
Hoa Sen University
64
Guideline 3 Take an actor and actor-goal perspective – “a set of use-case instances, where each instance is a sequence of actions a system performs that yields an observable result of value to a particular actor” Write requirements focusing on the users or actors of a system. Focus on understanding what the actor considers a valuable result.
Hoa Sen University
65
How to find use cases (Guideline 4) Choose the system boundary – Software, hardware, person, organization
Identify the primary actors – Goals fulfilled by using the system
Identify goals for each actor Define use cases that satisfy goals – User-goal level use cases will be one-to-one with user goals – Exception: CRUD (Create, Retrieve, Update, Delete) E.g., “edit user”, “delete user”, … Collapse into a single use case (e.g., Manage Users) Hoa Sen University
66
Choose the system boundary In the case study, the POS system itself is the system under design; Everything outside of it is outside the system boundary Identify what is outside would help to identify the boundary
Hoa Sen University
67
Find primary actor and goals Questions to help find 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 sales Process rentals Handle returns
Manager
Start up Shut down
System Admin
Add user Modify user
Sales activity System
Analyse sales and performance data
Hoa Sen University
68
Actors, Goals & Boundaries Enterprise Selling Things Checkout Service
Sales Tax Agency Goal: Collect taxes on sales
POS System Sales Activity System
Cashier
Customer
Goal: Buy items
Goal: Analyze sales and performance data
Hoa Sen University
Goal: Process sales
69
Valid or useful use cases Which of these is a valid use case? – Negotiate a Supplier Contract – Handle Returns – Log In – Move Piece on Game Board
All are valid, but at different level; better question is “what is a useful level to express use cases”
Hoa Sen University
70
Guideline 5: Tests What tests can help find useful use cases? – Boss Test Log in does not sounds like something that will make your boss happy
– The EBP Test Elementary Business Process – “A task performed by one person in one place at one time, in response to a business event, which adds measurable business value and leaves the data in a consistent states, e.g. Approved Credit or Price Order.
– The size test A use case is very seldom a single action or step. Hoa Sen University
71
Guideline 5 : Tests (cont’ed) Applying the tests – Negotiate a Supplier Contract Much broader and longer than an EBP
– Handle returns Ok with the boss. Seems like an EBP. Size is good
– Log In Not OK with the boss, no measurable business value
– Move Piece on Game Board Single step – fail the size test
Reasonable violations of the tests – It is sometimes useful to write separate subfunction-level use cases representing subtasks or steps within a regular EBP-level use case. Hoa Sen University
72
Applying UML: Use Case Diagram system boundary
communication
NextGen POS
Process Sale Customer
Payment Authorization Service
Handle Returns actor
«actor» Tax Calculator
Cashier
Cash In
«actor» Accounting System
Analyze Activity
«actor» HR System
Manager «actor» Sales Activity System
Manage Security
System Administrator
alternate notation for a computer system actor
Use case diagram is an Excellent picture of the system context. It serves as a communication tool that summarizes the behaviour of a system and its actors
Manage Users
. . .
use case
Hoa Sen University
73
Diagram notation For a use case context diagram, limit the use cases to usergoal level use cases.
Show computer system actors with an alternate notation to human actors. NextGen «actor» Payment Authorization Service
Process Sale Cashier
primary actors on the left
. . .
supporting actors on the right Hoa Sen University
74
Alternate actor notation
NextGen Process Sale
...
«system» Payment Authorization Service
Payment Authorization Service
«actor» Payment Authorization Service
Hoa Sen University
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.
75
The include relationship Partial behaviour that is common across several use cases – E.g., PayByCredit occurs in several use cases: Process Sale, Process Rental, and so on
Solution: represent as a separate use case – “Refactoring and linking text to avoid duplication” (Larman)
“Use include when you are repeating yourself in two or more separate use cases and you want to avoid repetition” (Fowler) Hoa Sen University
76
Example of include relationship UC1: Process Sale –… – Main Success Scenario: 1. Customer arrives at a POS checkout with goods and/or services to purchase. … 7. Customer pays and System handles payment
– Extensions: 7b. Paying by credit: Include Handle Credit Payment. 7c. Paying by check: Include Handle Check Payment
UC7: Process Rental –… – Extensions: 6b. Paying by credit: Handle Credit Payment Hoa Sen University
77
Included use case UC12: Handle Credit Payment – … – Level: sub-function – Main Success Scenario 1. Customer enters their credit account information 2. System sends payment authorization request to an external payment authorization service system and request payment approval …
– Extensions: 2a. System detects failure to collaborate with external system: – 1. system signals error to cashier – 2. Cashier asks customer for alternate payment
Hoa Sen University
78
The include relationship To decompose an overwhelmingly long use case into subunits to improve comprehension Using include with asynchronous event handling Eg. – – – – –
UC8: Process self-help check out … Main Success Scenario 1… Extensions: a* At any time, customer selects printing help: Present Printing Help
Hoa Sen University
79
Model include relationship in use case diagram NextGen POS
Process Sale Cashier
«include»
«include»
«actor» Accounting System
«include»
Customer
Handle Check Payment «include»
UML notation: the base use case points to the included use case
Handle Cash Payment «include»
Handle Credit Payment «include»
«actor» Credit Authorization Service
Process Rental
Handle Returns Manage Users ...
Hoa Sen University
80
The extend relationship How to add an extension to a use case that is frozen or too complicated? Solution: use extend to relate to an addition use case Describe where and under what condition the additional use case extends the behaviour of the base use case (use extension point)
Hoa Sen University
81
Example of extend relationship UC1: Process Sale (the base use case) – … – Extension Points: VIP Customer, step1. Payment, step 7. – Main Success Scenario: 1. Customer arrives at a POS checkout with goods and/or services to purchase
… 7. Customer pays and system handles payment …
UC15: Handle Gift Certificate Payment (the extending use case) – – – – –
... Trigger: Customer wants to pay with gift certificate Extension Points: Payment in Process Sale Level: subfunction Main Success Scenario: 1. Customer gives gift certificate to Cashier 2. Cashier enters gift certificate ID Hoa Sen University
82
Extend relationship in use case diagram Process Sale Extension Points: Payment VIP Customer
UML notation: 1. The extending use case points to the base use case.
«extend» Payment, if Customer presents a gift certificate Handle Gift Certificate Payment
Hoa Sen University
2. The condition and extension point can be shown on the line.
83
Extend vs. include relationships Direction of the relationship – For include relationship, the event triggering the target use case is described in the flow of event of the source use case (user-goal level) – For extend relationships, the event triggering the source (the extending) use case is described in the source use case( sub-function level). The base use case have no knowledge of the extending use case
The purpose of adding include and extend relationships is to reduce or remove redundancies from the use case model Hoa Sen University
84
Rectangle 8
Domain Model
Lecture 3
Hoa Sen University
85
Agenda
Recap Case Requirements Elaboration process Domain model – Introduction and definition – How to create a domain model
Hoa Sen University
86
Recap
Inception activities Different types of requirements Scenario & Use case Writing Use Cases Use Case Diagram Use case relationships
Hoa Sen University
87
Case requirements The requirements for the first iteration of the NextGen POS: – Implement a basic, key scenario of the Process Sale use case – Implement a Start Up use case as necessary to support the initialization needs of the iteration – Nothing fancy or complex is handled – No collaboration with external services – No complex pricing rules are applied Hoa Sen University
88
Case requirements Monopoly – Implement a basic, key scenario of the Play Monopoly Game use case: players moving around the squares of the board – Implement a start Up use case as necessary to support the initialization needs of the iteration – Two to eight players can play – A game is played as a series of rounds
Hoa Sen University
89
Case requirements Monopoly (cont) – Play the game for only 20 rounds – After the dice are rolled, the name of the player and the roll are displayed. When the player moves and lands on a square, the name of the player and the name of the square that the player landed on are displayed. – In iteration-1 there is no money, no winner or loser, no properties to buy or rent to pay, and no special squares of any kind – Square name will be “Go”, “Square 1”, “Square 2”,…“Square 39” Hoa Sen University
90
Incremental Development Incremental development for the same use case across iteration 1
2
3
. . .
Use Case Use Case Use Case Process Sale Process Sale Process Sale
Feature: Logging
A 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 Case Process Rentals
Hoa Sen University
91
Process: inception What happened in inception – Last only one week – Most actors, goals and use cases named – Most use cases written in brief format; 10-20% of the use cases are written in fully dressed detail – Recommendations on what components to buy/build/reuse, to be refined in elaboration
Technical proof-of-concept prototypes and other investigations to explore the technical feasibility of special requirements/ High-level candidate architecture and components proposed – NOT necessary to be final or correct Plan for the first iteration Hoa Sen University
92
Process: on to Elaboration What happens in Elaboration – The core, risky software architecture is programmed and tested – The majority of requirements are discovered and stabilized – The major risks are mitigated or retired – Commonly, 2 or more timeboxed iterations
Elaboration in one sentence – Build the core architecture, resolve the high-risk elements, define most requirements, and estimate the overall schedule and resources. Hoa Sen University
93
Process: on to Elaboration Best practices in elaboration – Do short timeboxed risk-driven iterations – Start programming early – Adaptively design, implement, and test the core and risky parts of the architecture – Test early, often, realistically – Write most of the use cases and other requirements in detail, through a series of workshops, once per elaboration iteration Hoa Sen University
94
Domain models Illustrates noteworthy concepts in a domain Drawn with UML class diagram As with all things in an agile modelling and UP spirit, a domain model is optional Input – Problem Description, Use Cases, …
Output – A set of class diagrams Hoa Sen University
95
Example concept or domain object
Sales LineItem
1
0..1
quantity
Item
Recordssaleof
*
1..* association
Stockedin
Containedin
1
1 Sale attributes
date time
Store address name
0..1
1
1
Houses
Paidby
1..*
1 Payment
Register
Capturedon
amount
1
Identifying a rich set of conceptual classes is at the heart of OO analysis Hoa Sen University
96
What is a domain model A domain model is a visual representation of conceptual classes or real-situation objects in a domain. – Various names conceptual models, domain object models, analysis object models
A domain model is illustrated with a set of CLASS DIAGRAMS in which no operations (method signatures) are defined
Hoa Sen University
97
Domain models is a visual dictionary Domain model provides a conceptual perspective – Domain objects or conceptual classes – Associations between conceptual classes – Attributes of conceptual classes
The information it illustrates could alternatively have been expressed in plain text
Hoa Sen University
98
Domain model is not a picture of software objects Domain model is a visualization of things in a realworld domain of interest Not suitable in a domain model – Software artefacts – Responsibilities or methods
visualization of a realworld concept in the domain of interest
Sale dateTime
it is a not a picture of a software class
o id av
SalesDatabase
o id av
Sale date time
software artifact; not part of domain model
software class; not part of domain model
print()
Hoa Sen University
99
What 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
concept's symbol
Sale date time
"A sale represents the event of a purchase transaction. It has a date and time."
Hoa Sen University
concept's intension
sale1 sale2
sale3
concept's extension
sale4
100
Domain model vs. Data model Data model – persistent data to be stored somewhere Domain model also include – Temporary object – Object with no attribute
Hoa Sen University
101
Motivation Help to understand the key concepts in a business or problem domain Lower representational gap with OO Modelling UP Domain Model Stakeholder's view of the noteworthy concepts in the domain. 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.
Payment
1
amount
Sale date time
inspires objects and names in
This reduces the representational gap. This is one of the big ideas in object technology.
1
Paysfor
Payment amount: Money
Sale 1
Paysfor
getBalance(): Money
1
date: Date startTime: Time getTotal(): Money . . .
UP Design Model The objectoriented developer has taken inspiration from the real world domain in creating software classes. Therefore, the representational gap between how stakeholders conceive the domain, and its representation in software, has been lowered.
Hoa Sen University
102
How to create a Domain Model Steps – Find the conceptual classes – Draw them as classes in a UML class diagram – Add associations and attributes
Hoa Sen University
103
Find conceptual classes Three strategies to find conceptual classes – Reuse or modify existing models There are published, well-crafted domain models and data models for common domains: inventory, finance, health.. Books: Analysis patterns by Martin Fowler, Data Model Patterns by David Hay, Data Model Resource Book by Len Silverston
– Use a category list – Identify noun phrases Hoa Sen University
104
Use a category list Use a conceptual class category list: – Physical or tangible objects Register, Airplane – Specifications, descriptions of things ProductSpecification, FlightDescription – Places Store, Airport – Transactions Sale, Payment, Reservation – etc. (see Table 9.1 for a fuller list) Hoa Sen University
105
Noun Phrase Identification Noun Phrase Identification [Abbot 83] – Analyse textual description of the domain
Identify nouns and noun phrases (indicate candidate classes or attributes) Caveats: – Automatic mapping isn’t possible – Textual descriptions are ambiguous! (different words may refer to the same class)
Hoa Sen University
106
Example: flow of event The customer enters a store with the intention of buying a toy for his 3 years old child Alice. Help must be available within less than one minute. The store owner gives advice to the customer. The advice depends on the age range of the child and the attributes of the toy. The customer selects a dangerous toy which is kind of unsuitable for the child. The store owner recommends a soft doll. Hoa Sen University
107
Mapping parts of speech to object model components Part of speech Proper noun Common noun Doing verb Being verb
Model component Instance Class Operation Inheritance
Having verb
Aggregation (Composition)
Examples Alice Customer, toy Buy, recommend Is a kind of, is one of Has, consists of, includes
Modal verb Adjective attributes
Constraints Attributes
Must be 3 years old
Hoa Sen University
108
Example: find and draw conceptual classes Case study: POS Domain – Input fully dressed use case model (excellent textual description of the domain) Iteration-1: success (cash-only) scenario of Process Sale use case.
– Strategy: category list – There is no such thing as a “correct” list. It is a somewhat ARBITRARY collection of domain vocabulary that the modellers consider noteworthy Hoa Sen University
109
Initial POS domain model Register
Item
Store
Sale
Sales LineItem
Cashier
Customer
Ledger
Cash Payment
Product Catalog
Product Description
Hoa Sen University
110
Initial Domain model of Monopoly game simulation
Hoa Sen University
111
Agile modelling style It is normal to miss significant conceptual classes during early domain modeling and to discover them later during DESIGN sketching or PROGRAMMING. We can maintain the model by drawing it with tool OFTEN, a long-life OO analysis domain model does not add value
Hoa Sen University
112
Include report objects? Receipt is a noteworthy term in POS domain It has duplicate information contained in sale and payment. Guidelines – In general, showing a report of other information in a domain model is not useful – However, it might has special role in terms of business rules. We might have a reason to show it in the model.
Hoa Sen University
113
Class or Attributes Class or attribute? – If we do not think of some conceptual class X as a number or text in the real world, X is probably a conceptual class, not an attributes
Hoa Sen University
114
Description Class What’s the rationale for representing the description or specification separately from the item In the following domain model, can you tell the difference between (description, price, itemID) and serial number? Item Worse
description price serial number itemID
ProductDescription description price itemID
1
Describes
Item
*
serial number
Hoa Sen University
Better
115
Description 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
Flight date number time
*
Flight date time
Hoa Sen University
Airport
Fliesto
*
1
name
FlightDescription
Describedby 1
Worse
Better
number
*
Describesflightsto
1 Airport name
116
Associations Definition – An association is a relationship between objects that indicates some meaningful and interesting connection – UML def.: associations are defined as “the semantic relationship between two or more classifiers that involve connections among their instances.” association
Register
1
Recordscurrent
Hoa Sen University
1
Sale
117
When to show association Associations for which knowledge of the relationship needs to be preserved for some duration – In the POS domain We need to remember what SalesLineItem instances are associated with a Sale. Cashier may look up ProductionDescription during the process of sale, but we do not need to remember who looked up what after the sales has been made.
– In the monopoly domain We need to remember what Square a Piece is on. Dice total may indicate a Piece how many steps to move on, what Square it will land, but we do not need to remember that
We should avoid showing too many associations Hoa Sen University
118
Associations and implementation There is no direct relationship between associations and implementation. Associations do not indicate a certain implementation construct. Many associations may be implemented in software differently
Hoa Sen University
119
Association Notation "reading direction arrow" it has no meaning except to indicate direction of reading the association label often excluded
Register
1
association name
Recordscurrent
0..1
Sale
multiplicity
Hoa Sen University
120
Naming association Name an association based on a ClassName-VerbPhrase-ClassName format Eg. – Sales paid-by CashPayment Bad alternative: Sales uses CashPayment
– Piece is-on Square Bad alternative: Piece has Square
Hoa Sen University
121
Applying UML: multiplicity Multiplicity defines how many instances of a class A can be associated with one instance of class B
Store
1
Stocks
*
Item
multiplicity of the role Hoa Sen University
122
Multiplicity 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.”
* 1..*
1..40
5
3, 5, 8
Hoa Sen University
T
zero or more; "many"
T
one or more
T
one to 40
T
exactly 5
T
exactly 3, 5, or 8
123
Multiplicity values Store
Stocks 1 or 0..1
*
Item
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 realworld domain) with validity checks. From this viewpoint, "1" may be the desired value.
Hoa Sen University
124
Multiple association between two classes
Flight
* *
Fliesto Fliesfrom
Hoa Sen University
1 Airport 1
125
Find association Use the common associations list – A is a physical part of B Square – Board
– A is a logical part of B SalesLineItem – Sale
– A uses or submanages B Cashier- Register
– A communicates with B Customer – Cashier
– etc. Hoa Sen University
126
POS partial domain model Recordssaleof Ledger
1
Product Catalog 1 Records accounts for
0..1 Sales LineItem
1
Store
1
Logs completed
1
*
Sale
1..*
Describes
*
1
1..*
Contains
Usedby
1 Containedin
1
Product Description
*
Stocks
Item
*
1..*
Houses
1..* Register
Capturedon 0..1 1
Paidby 1 CashPayment
1
1
Isfor
1
Workson
1
1
Customer
Cashier
Hoa Sen University
127
Monopoly partial domain model
Hoa Sen University
128
Attributes An attribute is a logical data value of an object When to show attribute – Include attributes that the requirements suggest or imply a need to remember information – Eg. Sale needs a dateTime attribute Store needs a name and address.
Hoa Sen University
129
UML notation Attributes are shown in the second compartment of the class box. Type and other information may optionally be shown Derived attribute – The total attribute in the Sale can be calculated from other information – It is worth noting down. Sale dateTime : Date / total : Money Private visibility attributes
Math + pi : Real = 3.14 {readOnly}
Public visibility readonly attribute with initialization Hoa Sen University
Person firstName middleName : [0..1] lastName Optional value 130
Suitable 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
Worse
Better
Worse
Better
Cashier
not a "data type" attribute
name currentRegister
Cashier
1
Uses
name
number
Flight
destination is a complex concept
destination
Flight
Hoa Sen University
Register
1
1
Fliesto
1
Airport
131
Data types as attributes We sometimes represent what may initially be considered a number or string as a new data type class in the domain model We can show the data type only in attribute compartment or as a separate class associated with another class. Address
ItemID OK
OK
Product Description
Product Description itemId : ItemID
1
1
Store
id manufacturerCode countryCode
1
1
street1 street2 cityName ...
Store address : Address
Hoa Sen University
132
Attributes are NOT foreign keys During implementation, there are many ways to relate objects, including foreign key, but the decision should be deferred till DESIGN stage. Worse
Better
Cashier
a "simple" attribute, but being used as a foreign key to relate to another object
name currentRegisterNumber
Cashier
1
Workson
name
1
Register number
Hoa Sen University
133
Modelling quantities Payment
not useful
amount : Number
Payment
* Payment amount : Quantity
Payment amount : Money
Hasamount
Quantity 1
amount : Number
quantities are pure data values, so are suitable to show in attribute section
*
Isin
Unit 1
...
better
variation: Money is a specialized Quantity whose unit is a currency
Hoa Sen University
134
Iterative and evolutionary domain model Is the domain model correct? – There is no such thing as a single correct domain model! – Domain model is incrementally evolve over several iterations. – In each iteration, the domain model is limited to the prior and current scenarios under consideration.
Hoa Sen University
135
Contracts and UML interaction diagrams Rectangle 8
Lecture 4
Hoa Sen University
136
Agenda System sequence diagram Operation Contract On to Object design – Interaction diagrams Sequence diagrams Communication diagrams
Hoa Sen University
137
System Sequence Diagram Sample UP Artifact Relationships Domain Model Sale
Business Modeling
Sales LineItem
1..*
1
date . . .
. . . . . .
quantity
Vision
UseCase Model Process Sale Process Sale
use case names
Cashier
Require ments
Use Case Diagram
1. Customer arrives ... 2. Cashier makes new sale. 3. ...
parameters and return value details
Use Case Text
Glossary
system events : System Operation: enterItem(…) Postconditions: . . .
: Cashier
system operations
Operation Contracts
Supplementary Specification
make NewSale() enterItem (id, quantity)
System Sequence Diagrams
starting events to design for : Register
Design
Design Model
: ProductCatalog
: Sale
enterItem (itemID, quantity) spec = getProductSpec( itemID ) addLineItem( spec, quantity )
Hoa Sen University
138
What is System Sequence Diagram A diagram that shows, for ONE particular scenario of a use case, the events that external actors generate, their order, and INTER-system events. (not detailed method calls between objects) Describe what a system does without explaining why
Hoa Sen University
139
System sequence diagram system as black box the name could be "NextGenPOS" but "System" keeps it simple the ":" and underline imply an instance, and are explained in a later chapter on sequence diagram notation in the UML external actor to system
Process Sale Scenario
:System
: Cashier makeNewSale a UML loop interaction frame, with a boolean guard expression
loop
[ more items ]
enterItem(itemID, quantity) description, total
endSale 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 makePayment(amount)
a message with parameters it is an abstraction representing the system event of entering the payment data by some mechanism
change due, receipt
Hoa Sen University
140
Use Cases and SSDs : Cashier
:System
makeNewSale
Simple cashonly 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 34 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. ...
Process Sale Scenario
loop
[ more items ]
enterItem(itemID, quantity) description, total
endSale total with taxes makePayment(amount)
change due, receipt
Hoa Sen University
141
Choosing events and operation name System events should be expressed at the abstract level of intention rather than in terms of the physical input device
better name
:System
: Cashier enterItem(itemID, quantity)
scan(itemID, quantity) worse name
Hoa Sen University
142
Iterative and Evolutionary SSDs Do not create SSDs for all scenarios (remember agile style) SSDs are part of the Use-Case Model – Visualization of the interactions implied in the use cases scenarios
Hoa Sen University
143
Operation Contract Sample UP Artifact Relationships Domain Model Sale
Business Modeling
1..*
1
date . . .
Sales LineItem
. . . . . .
quantity
Vision
UseCase Model Process Sale Process Sale
use case names
Cashier
Require ments
Use Case Diagram
1. Customer arrives ... 2. ... 3. Cashier enters item identifier.
system events
ideas for the post conditions
the domain objects, attributes, and associations that undergo changes
Operation: enterItem(…) Postconditions: . . .
starting events to design for, and more detailed requirements that must be satisfied by the software Design
Glossary
Use Case Text requirements that must be satisfied by the software
: System : Cashier
system operations
Operation Contracts
Supplementary Specification
make NewSale() enterItem (id, quantity)
System Sequence Diagrams
: Register
Design Model
: ProductCatalog
: Sale
enterItem (itemID, quantity) spec = getProductSpec( itemID ) addLineItem( spec, quantity )
Hoa Sen University
144
Example Contract Contract CO2: enterItem
Operation: Cross References: Preconditions: Postconditions: – – – –
enterItem(itemID: ItemID, quantity: integer) Use Cases: Process Sale There is a sale underway.
A SalesLineItem instance sli was created (instance creation). sli was associated with the current Sale (association formed). sli.quantity became quantity (attribute modification). sli was associated with a ProductDescription, based on itemID match (association formed).
Hoa Sen University
145
Contract definition A description of each section in a contract is shown in the following schema. Operation: Cross References: Preconditions:
Postconditions:
Name of operation, and parameters Use cases this operation can occur within Noteworthy assumptions about the state of the system or objects in the Domain Model before execution of the operation. These are nontrivial assumptions the reader should be told. This is the most important section. The state of objects in the Domain Model after completion of the operation. Discussed in detail in a following section.
Hoa Sen University
146
Contract procedure To make contract – Identify System Operations from SSD – For system operations that are complex or subtle in their results or are not clearly express in use cases, construct a contract – To describe the post conditions, use the following categories Instance creation and deletion Attribute change of value Associations (to be precise, UML links) formed and broken Hoa Sen University
147
System operations Process Sale Scenario :System
: Cashier makeNewSale()
loop
[ more items ]
enterItem(itemID, quantity)
description, total
these input system events invoke system operations the system event enterItem invokes a system operation called 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
endSale() total with taxes makePayment(amount)
change due, receipt
Hoa Sen University
148
Process Sale: makeNewSale Contract CO1: makeNewSale
Operation: Cross References: Preconditions: Postconditions:
makeNewSale() Use Cases: Process Sale none
– A Sale instance s was created (instance creation). – s was associated with a Register (association formed). – Attributes of s were initialized.
Hoa Sen University
149
Object design introduction How do developers design objects – – – –
Code Design-while-coding Draw, then code Only draw
Agile modelling: reduce drawing overhead and model to understand and communicate – Modeling with others – Creating several models in parallel – Using an internal wiki (www.twiki.org )
How much time spent drawing UML before coding? – For a three-week timeboxed iteration, spend a few hours or at most one day near the start of the iteration drawing UML for the hard, creative parts of the detailed object design
Hoa Sen University
150
Static vs. dynamic modelling Dynamic models help design the logic, the behavior of the code or the method bodies – Sequence diagram, communication diagram
Static models help design the definition of packages, class names, attributes, and method signatures – UML class diagram
Hoa Sen University
151
Interaction diagrams Generalization of two more specialized UML diagram types – Sequence diagrams – Communication diagrams
Illustrate how objects collaborate via messages and methods
Hoa Sen University
152
Sequence vs. Communication diagram Sequence diagrams illustrate interactions in a kind of fence format
: A
myB : B
doOne doTwo
– Easier to see the call sequence – Large set of detailed notation options
Communication diagrams illustrate interactions in a graph or network format
doThree
doOne
: A 1: doTwo 2: doThree
– More space-efficient
myB : B
Hoa Sen University
153
Common notation: participants – lifeline box lifeline box representing an unnamed instance of class Sale
:Sale
lifeline box representing a named instance
s1 : Sale
lifeline box representing an instance of an ArrayList class, parameterized (templatized) to hold Sale objects
sales: ArrayList<Sale>
lifeline box representing one instance of class Sale, selected from the sales ArrayList <Sale> collection
sales[ i ] : Sale
lifeline box representing the class Font, or more precisely, that Font is an instance of class Class – an instance of a metaclass «metaclass» Font
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
x : List
related example
Hoa Sen University
154
Sequence diagram notation Lifeline boxes and lifelines Messages – Synchronous message – Found message
Focus of control and execution specification bars
: Register doX
a found message whose sender will not be specified
: Sale
doA doB doC doD
execution specification bar indicates focus of control
Hoa Sen University
typical sychronous message shown with a filledarrow line
155
Sequence diagram notation Illustrating reply or returns
: Register
– Using the message syntax returnVar = message(parameter). doX
– Using a reply message line
Message to “self” or “this”
: Sale
d1 = getDate getDate
public class Register{ public void doX(){ … clear(); … } public void clear(){ } }
aDate
: Register doX clear
Hoa Sen University
156
Sequence diagram notation : Register
note that newly created objects are placed at their creation "height"
: Sale
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
makePayment(cashTendered)
create(cashTendered)
: Payment
authorize
: Sale create(cashTendered)
: Payment
... «destroy»
Hoa Sen University
X
the «destroy» stereotyped message, with the large X and short lifeline indicates explicit object destruction
157
Sequence diagram notation Diagram frames in UML sequence diagrams – Support conditional and looping construct : A
: B makeNewSale
a UML loop frame, with a boolean guard expression
loop
[ more items ]
enterItem(itemID, quantity) description, total
endSale
Hoa Sen University
158
Sequence diagram notation Common frame operators Frame operator Alt
Meaning
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
Alternative fragment for mutual exclusion conditional logic expressed in the guards
Hoa Sen University
159
Sequence diagram notation Conditional messages public class foo{ Bar bar = new Bar(); … opt public void m1(){ bar.xx(); if (color.equals(“red”)) bar.calculate(); bar.yy(); } }
: Foo
: Bar xx
[ color = red ] calculate
yy
: Foo
: Bar xx
[ color = red ] calculate
UML1.x style yy
Hoa Sen University
160
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(); } }
: A
: B
: C
doX alt
[ x < 10 ]
[ else ]
Hoa Sen University
calculate
calculate
161
Sequence diagram notation Iteration over a collection lineItems[i] : SalesLineItem
: Sale t = getTotal
loop
[ i < lineItems.size ]
st = getSubtotal
i++
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
Hoa Sen University
162
Sequence diagram notation public class Sale{ private List<salesLineItem> lineItems = new ArrayList<salesLineItem>(); public Money getTotal(){ Money total = new Money(); Money subtotal = null; for (SalesLineItem lineItem: lineItems){ subtotal = lineItem.getSubtotal(); total.add(subtotal); } lineItems[i] : } : Sale SalesLineItem }
t = getTotal
loop
st = getSubtotal
Hoa Sen University
163
Sequence diagram notation Nesting frames : Foo
: Bar xx
opt
[ color = red ]
loop(n)
calculate
Hoa Sen University
164
Sequence diagram notation Relate interaction diagrams An interaction occurrence ( an interaction use) is a reference to an interaction within another interaction. Two related frames – A frame around an entire sequence diagram, labelled with the tag sd and a name, – A frame tagged ref, called a reference, that refers to another named sequence diagram;
Hoa Sen University
165
Sequence diagram notation sd AuthenticateUser
: A doX
: B
: B
: C
: C
authenticate(id) doA authenticate(id)
doM1
doB ref
ref
doM2
AuthenticateUser
sd DoFoo
DoFoo
: B
: C
interaction occurrence
doX
note it covers a set of lifelines
doY
note that the sd frame it relates to has the same lifelines: B and C
doZ
Hoa Sen University
166
Sequence diagram notation Messages to classes to invoke static methods public class Foo{ public void doX(){ Locale[] locales = Calendar.getAvailableLocales(); .. } }
message to class, or a static method call doX : Foo
1: locs = getAvailableLocales
Hoa Sen University
«metaclass» Calendar
167
Sequence diagram notation Payment {abstract} Payment is an abstract superclass, with concrete subclasses that implement the polymorphic authorize operation
Polymorphic messages and cases
authorize() {abstract} ...
CreditPayment
DebitPayment
authorize() ...
authorize() ...
object in role of abstract superclass
polymorphic message
:Register doX
:DebitPayment
:Payment {abstract}
authorize
stop at this point – don’t show any further details for this message
:Foo
authorize
:CreditPayment
:Bar
authorize
doA
doX
doB
separate diagrams for each polymorphic concrete case
Hoa Sen University
168
Sequence diagram notation Asynchronous and synchronous calls – Call does not wait for a response – Asynchronous calls are used in multi-thread application – Show as a stick arrow message – It is common for modeler to use stick arrow to represent synchronous message – Do not assume the shape of the arrow is correct
Hoa Sen University
169
Collaboration diagram notation Links
1: makePayment(cashTendered) 2: foo
: Register
2.1: bar
– A connection path between two objects – Messages flow along link
:Sale
link line
Messages – Message between objects is represented with a message expression and small arrow indicating the direction of the message – A sequence number is added to show the sequential order of messages in the current thread of control – Many messages may flow along a same single link
msg1
: Register
1: msg2 2: msg3 3: msg4 3.1: msg5
:Sale
all messages flow on the same link
Hoa Sen University
170
Collaboration diagram notation (cont) msg1
Message to “self” or “this” Creation of instances
: Register
1: clear
– Use a message named create for this purpose
Create message may have parameters – Indicates a constructor call with parameters in Java
create message, with optional initializing parameters. This will normally be interpreted as a constructor call.
1: create(cashier ) : Register
:Sale
1: create(cashier ) : Register
: Register
:Sale {new}
«create» 1: make(cashier)
:Sale
if an unobvious creation message name is used , the message may be stereotyped for clarity
Hoa Sen University
171
Collaboration diagram notation (cont) Message number sequencing – OK to use flat numbering style or – Nested decimal numbers Clarify whether a message is called within another message msg1
: A
1: msg2
: B
1.1: msg3
not numbered legal numbering
Hoa Sen University
: C
172
Collaboration diagram notation (cont) first
second third
msg1
1: msg2
: A
: B 1.1: msg3 2.1: msg5
2: msg4
fourth
: C fifth
2.2: msg6 sixth
Hoa Sen University
: D
173
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
conditional message, with test message1 1 [ color = red ] : calculate
: Foo
unconditional after either msg2 or msg4
: E
: Bar
1a and 1b are mutually exclusive conditional paths
2: msg6 msg1
Hoa Sen University
1a [test1] : msg2 : A
: B
1b [not test1] : msg4
: D
1b.1: msg5
1a.1: msg3
: C
174
Collaboration diagram notation (cont) Iteration or Looping – Use a “*” to signify iteration runSimulation
: Simulator
1 * [ i = 1..n ]: num = nextInt
: Random
iteration is indicated with a * and an optional iteration clause following the sequence number
Hoa Sen University
175
Collaboration diagram notation (cont) Iteration over a collection t = getTotal
: Sale
1 * [i = 1..n]: st = getSubtotal
this iteration and recurrence clause indicates we are looping across each element of the lineItems collection.
t = getTotal
: Sale
lineItems[i]: SalesLineItem
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.
1 *: st = getSubtotal
lineItems[i]: SalesLineItem
Less precise, but usually good enough to imply iteration across the collection members Hoa Sen University
176
Collaboration diagram notation (cont) Messages to a Class Object message to class, or a static method call doX : Foo
1: locs = getAvailableLocales
Hoa Sen University
«metaclass» Calendar
177
Collaboration diagram notation (cont) Polymorphic messages and cases polymorphic message
doX
:Register
stop at this point – don’t show any further details for this message
authorize
:Payment {abstract}
authorize :DebitPayment
object in role of abstract superclass
authorize doA doB
:Foo
:CreditPayment
doX
:Bar
separate diagrams for each polymorphic concrete case
Hoa Sen University
178
Collaboration diagram notation (cont) Asynchronous and Synchronous calls startClock :ClockStarter 1: create 2: run :Clock
3: runFinalization
System : Class
asynchronous message active object
Hoa Sen University
179
Rectangle 8
Design class diagram
Lecture 5
Hoa Sen University
180
Agenda Notations Dependency Interaction and Class diagrams
Hoa Sen University
181
Design Class Diagram UML class diagram can be used in multiple perspectives. Domain Model conceptual perspective
Register
1
Captures
1
...
Register Design Model
...
DCD; software perspective
endSale() enterItem(...) makePayment(...)
Sale time isComplete : Boolean /total
Sale time isComplete : Boolean currentSale /total 1
Hoa Sen University
makeLineItem(...)
182
Attributes in UML using the attribute text notation to indicate Register has a reference to one Sale instance
OBSERVE: this style visually emphasizes the connection between these classes
Sale
Register currentSale : Sale
...
...
...
Register
Sale 1
...
currentSale
...
... ...
using the association notation to indicate Register has a reference to one Sale instance
thorough and unambiguous, but some people dislike the possible redundancy
Register currentSale : Sale ...
Hoa Sen University
Sale 1 currentSale
... ...
183
Attributes in UML Attributes are usually assumed private if no visibility is given Attributes-as-association line has – A navigability arrow – A multiplicity at the target end, but not the source end – A role name to show the attribute name – No association Name
Hoa Sen University
184
Domain Model vs. DCD the association name, common when drawing a domain model, is often excluded (though still legal) when using class diagrams for a software perspective in a DCD
UP Domain Model conceptual perspective
UP Design Model DCD software perspective
Register
Sale
1 Capturescurrentsale 1
id : Int
time : DateTime
Register
Sale 1
id: Int
currentSale
...
Hoa Sen University
time: DateTime ...
185
Collection attributes public class Sale{ private List <SalesLineItem> lineItems = new ArrayList<SalesLineItem>(); } Sale SalesLineItem } time: DateTime lineItems : SalesLineItem [1..*] or lineItems : SalesLineItem [1..*] {ordered}
Two ways to show a collection attribute
... ...
...
Sale time: DateTime ...
1..* lineItems {ordered, List}
SalesLineItem ... ...
notice that an association end can optionally also have a property string such as {ordered, List}
Hoa Sen University
186
Methods Method signature is shown in the third compartment of UML class box Should correspond with the messages in interaction diagram «method» // pseudocode or a specific language is OK public void enterItem( id, qty ) { ProductDescription desc = catalog.getProductDescription(id); sale.makeLineItem(desc, qty); }
Hoa Sen University
Register ... endSale() enterItem(id, qty) makeNewSale() makePayment(cashTendered)
187
Note Symbol & Operation issues Note Symbols – May represent several things A UML note or comment A UML constraint A method body
Operation issues in DCDs – The create operation (Constructor) See example in the SuperclassFoo class
– Operations to access attributes Common to ignore them.
Hoa Sen University
188
Keywords A UML keyword is a textual adornment to categorize a model element Usually show in guillemet (« »), sometimes are shown in curly braces. It is OK to define your own keyword Many people use it same as stereotype or tag in UML 1 Keyword
Meaning
Example usage
{abstract}
Classifier is an abstract class
In class diagram, above classifier name
«interface»
Classifier is an interface
In class diagram, above classifier name
Hoa Sen University
189
Generalization, abstract class, abstract operation In DCD generalization implies inheritance from the super class to subclass Abstract class and operations can be shown with an {abstract} keyword or by italicizing the name Final classes and operations are shown with the {leaf} keyword
Hoa Sen University
190
Dependency A dependency exists between two elements if changes to the definition of one element (the supplier) may cause changes to the other (the client) Various reason for dependency – Class send message to another – One class has another as its data – One class mention another as a parameter to an operation – One class is a superclass or interface of another
Hoa Sen University
191
When to show dependency Be selective in describing dependency Many dependencies are already shown in other format Use dependency to depict global, parameter variable, local variable and static-method. Use dependencies when you want to show how changes in one element might alter other elements Hoa Sen University
192
Dependency example public class Sale { public void updatePriceFor( ProductionDescription desc) { Money basePrice = desc.getPrice(); //... the Sale has parameter visibility to a ProductDescription, and thus some kind of } dependency }
ProductDescription ...
Sale
...
... updatePriceFor( ProductDescription ) ...
SalesLineItem 1..* lineItems
Hoa Sen University
... ... 193
Dependency example (cont) public class Foo{ public void doX(){ System.runFinalization(); //.. } the doX method invokes the runFinalization static method, and thus has a dependency on } the System class
System Foo
...
... runFinalization() ...
doX() ...
Hoa Sen University
194
Dependency labels There are many varieties of dependency, use keywords to differentiate them Different tools have different sets of supported dependency keywords. – <
> the source calls an operation in the target – <<use>> the source requires the targets for its implementation – <<parameter>> the target is passed to the source as parameter. Hoa Sen University
195
Interface Abstract definition of purely functional interfaces They do not define any attributes or associations They have no instances. They define a set of abstract operations They are an important aid for dividing software development between different teams (design by contract)
Hoa Sen University
196
Constraints
three ways to show UML constraints Stack size : Integer { size >= 0 } push( element ) pop() : Object
{ post condition: new size = old size + 1 }
{ post condition: new size = old size – 1 }
Hoa Sen University
197
Template Classes public class Board{ private List <Square> squares = new ArrayList<Square>(); the attribute type may be expressed in official UML, with the template binding K parameterized or template //.. «interface» syntax requiring an arrow interfaces and classes List or } in another language, such as Java K is a template parameter clear() ...
Board anonymous class with template binding complete
ArrayList clear() ...
ArrayList
T
squares : List or squares : List<Square> ...
elements : T[*] ... clear() ...
for example, the elements attribute is an array of type T, parameterized and bound before actual use.
there is a chance the UML 2 “arrow” symbol will eventually be replaced with something else e.g., ‘=’
Hoa Sen University
198
User-defined compartments DataAccessObject id : Int ... doX() ... exceptions thrown DatabaseException IOException responsibilities serialize and write objects read and deserialize objects ... Hoa Sen University
199
Interaction and Class Diagrams : Register
: Sale
makePayment(cashTendered) makePayment(cashTendered) messages in interaction diagrams indicate operations in the class diagrams
Register ... makePayment(…) ...
Sale 1 currentSale
Hoa Sen University
...
classes identified in the interaction diagrams are declared in the class diagrams
makePayment(…) ...
200
Rectangle 8
Object Design
Lecture 6
Hoa Sen University
201
Agenda Object design basics Monopoly game design and GRASP principles introduction GRASP principles in POS projects
Hoa Sen University
202
Object Design “Identify requirements, create a domain model, add methods to the software classes, define messages to meet requirements…” Too Simple! – What methods belong where? – How do we assign responsibilities to classes?
The critical design tool for software development is a mind well educated in design principles and patterns.
Hoa Sen University
203
Object Design: input POS project inputs – Use case text of Process Sale Defines the behaviour
– System sequence diagram Identify the system operation messages
– Supplementary specification Defines non-functional goals
– Glossary Data format, data related with UI and database
– Domain model initial attempt of software object in the domain layer of software architecture Hoa Sen University
204
Object Design: activities and output Design activities – Coding immediately Using test-driven development
– Short UML modelling Apply OO Design principles and design patterns
Design output – UML diagrams for difficult parts of the system – UI prototypes and database models
Hoa Sen University
205
Responsibilities Contract or obligation of a class What must a class “know”? [knowing responsibility] – Private encapsulated data – Related objects – Things it can derive or calculate
What must a class “do”? [doing responsibility] – Take action (create an object, do a calculation) – Initiate action in other objects – Control/coordinate actions in other objects
Responsibilities are assigned to classes of objects during object design
Hoa Sen University
206
Examples of responsibilities “A Sale is responsible for creating SalesLineItems” (doing) “A Sale is responsible for knowing its total” (knowing) These are related to operations, attributes, associations in the domain model
Hoa Sen University
207
Domain model and responsibilities Domain model illustrates attributes and associations => inspires the “knowing” responsibilities Responsibilities are defined in conceptual level Methods fulfil responsibilities – Alone – Through collaboration with other objects and methods Hoa Sen University
208
Responsibilities and UML : Sale
makePayment(cashTendered)
create(cashTendered)
: Payment
abstract, implies Sale objects have a responsibility to create Payments
Hoa Sen University
209
GRASP principles General Responsibility Assignment Software Patterns The five basic principles in Monopoly game design: – Creator – Information Expert – High Cohesion – Low Coupling – Controller Hoa Sen University
210
Creator: problem Problem – Who creates the Square object
Start point: domain model
Hoa Sen University
211
Creator: principle Problem – Who creates an A object
Solution – Assign class B the responsibility to create an instance of class A if one of these is true B “contains” A B records A B closely uses A B has the Initializing data for A
Hoa Sen University
212
Creator: Solution
Hoa Sen University
213
Information Expert Problem – Who knows about a Square object, given a key? – Alternatively, who should be the receiver of message getSquare(name)
Board knows about all squares – Board has the information necessary to fulfil this responsibility
Hoa Sen University
214
Information Expert: principle Problem – What is a general principle of assigning responsibilities to objects
Solution – Assign a responsibility to the class that has the information needed to fulfil it
Hoa Sen University
215
Low coupling Problem – How to reduce the impact of change, to support low dependency, and increase reuse?
Solution – Assign a responsibility so that coupling remains low
Hoa Sen University
216
Coupling How strongly one element is connected to, has knowledge of, or depends on other elements Illustrated as dependency relationship in UML class diagram
Hoa Sen University
217
Example of poor design
Hoa Sen University
218
Controller Problem – What first object beyond the UI layer receives and coordinates (“controls”) a system operation
Solution – Assign the responsibility to an object representing one of these choices – Represents the overall system, root object, device or subsystem – Represents a use case scenario within which the system operations occurs
Hoa Sen University
219
Example
Hoa Sen University
220
Example
Hoa Sen University
221
Example
Hoa Sen University
222
High cohesion Problem – How to keep objects focused, understandable, and manageable, and as a side effect, support Low Coupling?
Solution – Assign responsibilities so that cohesion remains high
Hoa Sen University
223
Cohesion How strongly related and focused the responsibilities of an element are Formal definition (calculation) of cohesion – Cohesion of the two methods is defined as the intersection of the sets of instance variables that are used by the methods – If an object has different methods performing different operations on the same set of instance variables, the class is cohesive
Hoa Sen University
224
Example
Hoa Sen University
225
Applying GRASP to POS design Sale
Creator – Example: Who should be responsible for creating a SalesLineItem instance – Solution: Sale contains many SalesLineItem objects.
time 1 Contains 1..* Sales LineItem
*
Describedby
quantity : Register
1
Product Description description price itemID
: Sale
makeLineItem(quantity)
Hoa Sen University
create(quantity)
: SalesLineItem
226
GRASP in POS project Information Expert Example
Sale
– Who should be responsible for knowing the grand total of a sale – What information do we need to compute the grand total
time 1 Contains 1..* Sales LineItem quantity
*
Describedby
1
Product Description description price itemID
SalesLineItem
Hoa Sen University
227
Create diagrams in parallel t = getTotal
Sale
:Sale time ... New method
getTotal()
The new responsibility is conveyed by an operation in an interaction diagram. A new method is created in the design class to express this.
Hoa Sen University
228
Create diagram in parallel this notation will imply we are iterating over all elements of a collection
Sale time ...
t = getTotal
: Sale
1 *: st = getSubtotal
lineItems[ i ] : SalesLineItem
getTotal()
SalesLineItem quantity New method
getSubtotal()
Responsibility for each subtotal is assigned to the SalesLineItem Hoa Sen University
229
Create diagrams in parallel Sale time ... t = getTotal
: Sale
lineItems[ i ] : SalesLineItem
1 *: st = getSubtotal
1.1: p := getPrice()
getTotal()
SalesLineItem quantity
:Product Description
Responsibility for each item price is assigned to the ProductSpecification New method
Hoa Sen University
getSubtotal() Product Description description price itemID getPrice()
230
GRASP in POS projects How should we assignment responsibilities of creating Payment instance and associate it with the Sale.
Hoa Sen University
231
Options makePayment()
: Register
1: create()
p : Payment
2: addPayment(p)
makePayment()
: Register
:Sale
1: makePayment()
:Sale
1.1. create()
:Payment
Hoa Sen University
232
GRASP in POS project presses button : Cashier actionPerformed( actionEvent )
UI Layer
system operation message
:SaleJFrame
1: enterItem(itemID, qty)
controller
Domain Layer
:Register
1.1: makeLineItem(itemID, qty)
Hoa Sen University
:Sale
233
Controller Choices Represents the overall “system”, “root object”, device or subsystem
enterItem(id, quantity)
enterItem(id, quantity)
– Register
:Register
:ProcessSaleHandler
Represents a receiver or handler of all system events of a user case scenario Hoa Sen University
234
Allocate system operations System endSale() enterItem() makeNewSale() makePayment() makeNewReturn() enterReturnItem() . . .
system operations discovered during system behavior analysis
Register ... endSale() enterItem() makeNewSale() makePayment() makeNewReturn() enterReturnItem() . . .
allocation of system operations during design, using one facade controller
ProcessSale Handler
System endSale() enterItem() makeNewSale() makePayment() enterReturnItem() makeNewReturn() . . .
HandleReturns Handler
...
...
endSale() enterItem() makeNewSale() makePayment()
enterReturnItem() makeNewReturn() . . .
allocation of system operations during design, using several use case controllers
Hoa Sen University
235
Choosing a Controller Façade controller – PRO: all events handled in one place – CON: can become too bloated
Use-case controller – PRO: manage many different events across different processes – CON: adds additional classes; events can’t be managed (e.g. logged) in one place
Hoa Sen University
236
Desirable coupling of UI layer to domain layer presses button : Cashier actionPerformed( actionEvent )
UI Layer
system operation message
:SaleJFrame
1: enterItem(itemID, qty)
controller
Domain Layer
:Register
1.1: makeLineItem(itemID, qty)
Hoa Sen University
:Sale
237
Less desirable coupling presses button Cashier actionPerformed( actionEvent )
UI Layer
:SaleJFrame
It is undesirable for an interface layer 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.
1: makeLineItem(itemID, qty)
Domain Layer
:Sale
SaleJFrame should not send this message.
Hoa Sen University
238
High cohesion Reconsider the problem presented and solved by “Low coupling” principle : Register makePayment()
: Sale
create()
p : Payment
addPayment( p )
From previous practice, Register is mainly responsible for handling System operations such as enterItem, endSale, and so on; The responsibility of creating payment instance is not cohesive with other responsibilities Hoa Sen University
239
Desirable solution : Register
: Sale
makePayment() makePayment()
Hoa Sen University
create()
: Payment
240
Rectangle 8
Use case realization
Lecture 7
Hoa Sen University
241
Agenda Recap Use Case Realization with GRASP – POS project – Monopoly Game project
Designing for visibility
Hoa Sen University
242
Recap Design Class Diagram – DCD vs. DM – Four different types of notations indicating inter-class relationship
GRASP – Assigning Responsibilities to classes Some object needs to be created Some action needs to be taken
Hoa Sen University
243
Use-Case Realization “…describes how a particular use case is realized within the design model, in terms of collaborating objects” [RUP] Individual scenarios are realized Use case -> System events -> System sequence diagram -> System operation contracts -> Interaction diagrams -> Design classes
Hoa Sen University
244
System operation makeNewSale, etc., are the system operations from the SSD each major interaction diagram starts with a system operation going into a domain layer controller object, such as Register
makeNewSale Window objects or GUI widget objects or Web control objects
. . .
enterItem
endSale
makePayment UI LAYER
:Register
:Register
:Register
:Register
1: ???
1: ???
1: ???
1: ???
DOMAIN LAYER
The system operations in the SSD are used as the start messages into the domain layer If communication diagrams are used, one per system operation Same for sequence diagram
Hoa Sen University
245
One diagram per system operation : Register makeNewSale
Window objects or GUI widget objects or Web control objects
create
: Sale
. . . : Register enterItem(...)
: ProductCatalog
desc = getProductDesc( itemID ) . . .
UI LAYER
DOMAIN LAYER
Hoa Sen University
246
Design makeNewSale Choosing the controller class – A façade controller is satisfactory if there are only a few system operations – Use Register here.
Creating a new Sale – Register create Sale – Sale create a collection to store SalesLineItems
Hoa Sen University
247
Design makeNewSale by Creator and Controller
Register creates a Sale by Creator
:Register
makeNewSale create
by Creator, Sale creates an empty collection (such as a List) which will eventually hold SalesLineItem instances
:Sale create
lineItems : List<SalesLineItem>
this execution specification is implied to be within the constructor of the Sale instance
Hoa Sen University
248
Design: enterItem
Contract CO2: enterItem Operation: enterItem(itemID : ItemID, quantity : integer) Cross References: Use Cases: Process Sale Preconditions: There is an underway sale. Postconditions: – – – –
A SalesLineItem instance sli was created (instance creation). sli was associated with the current Sale (association formed). sli.quantity became quantity (attribute modification). sli was associated with a ProductDescription, based on itemID match (association formed).
Hoa Sen University
249
Design enterItem Choosing controller class Display item description and price (ignore at this stage) Create a new SalesLineItem Finding a ProductDescription Visibility to ProductCatalog Temporary and persistent storage – We can defer database design and use temporary memory object instead Hoa Sen University
250
Design enterItem by Creator
by Controller
enterItem(id, qty)
:Register
2: makeLineItem(desc, qty)
1: desc = getProductDesc(id)
:Sale
2.1: create(desc, qty) :Product Catalog
by Expert
sl: SalesLineItem 1.1: desc = get(id)
2.2: add(sl)
: Map
lineItems : List<SalesLineItem>
Hoa Sen University
add the newly created SalesLineItem instance to the List
251
Partial Design Class Diagram ProductCatalog 1 catalog
... getProductDesc(...)
ProductDescription
descriptions description : Text {Map} price : Money 1..* itemID: ItemID ...
description 1 Sale Register ... enterItem(...) ...
currentSale 1
isComplete : Boolean time : DateTime makeLineItem(...) ...
Hoa Sen University
lineItems {ordered}
1..*
SalesLineItem quantity : Integer ...
252
Design endSale «method» public void getTotal() { int tot = 0; for each SalesLineItem, sli tot = tot + sli.getSubtotal(); return tot }
tot = getTotal
:Sale
1 *[ i = 1..n]: st = getSubtotal
lineItems[ i ] : SalesLineItem 1.1: pr = getPrice :ProductDescription
Hoa Sen University
253
Design makePayment
Contract CO4: makePayment Operation: makePayment( amount: Money ) Cross References: Use Cases: Process Sale Preconditions: There is an underway sale. Postconditions: – – – –
A Payment instance p was created (instance creation). p.amountTendered became amount (attribute modification). p was associated with the current Sale (association formed). The current Sale was associated with the Store (association formed); (to add it to the historical log of completed sales).
Hoa Sen University
254
Design makePayment Creating payment by Controller
makePayment(cashTendered)
by Creator and Low Coupling
:Register
1: makePayment(cashTendered)
:Sale
1.1: create(cashTendered) :Payment
Hoa Sen University
255
Design makePayment Sale
Logging a sale
Sale
...
...
...
...
*
Logscompleted
Logscompleted
1
* 1
Store
SalesLedger
...
...
addSale(s : Sale) ...
addSale(s : Sale) ...
Store is responsible for knowing and adding completed Sales. Acceptable in early development cycles if the Store has few responsibilities.
Hoa Sen University
SalesLedger is responsible for knowing and adding completed Sales. Suitable when the design grows and the Store becomes uncohesive.
256
Design makePayment note that the Sale instance is named 's' so that it can be referenced as a parameter in messages 2 and 2.1
makePayment(cashTendered)
:Register
1: makePayment(cashTendered)
2: addSale(s)
s :Sale
1.1: create(cashTendered)
by Expert
:Payment :Store 2.1: add(s) completedSales: List<Sale>
Hoa Sen University
257
Design makePayment Calculating the balance – Who is responsible for knowing the balance? To calculate, sale total and payment tendered are required Sale and Payment are partial Experts
Consider coupling… – Sale already has visibility into Payment – Payment does not have visibility into Sale – Giving Sale primary responsibility doesn’t increase overall coupling Hoa Sen University
258
getBalance design
{ bal = pmt.amount s.total } bal = getBalance
s :Sale
1: amt = getAmount
pmt: Payment
2: t = getTotal
Hoa Sen University
259
Object Design: startUp Initial system operation Delay until all other system operations have been considered – What objects need to be there through out the use case – What associations need to be there through out the use case
Create a set of domain objects that need to be there to support the use case execution Find a suitable initial object and request that object to create a set of other objects Do the initialization design last
Hoa Sen University
260
Create Initial Domain Object public class Main { public static void main( String[] args ) { // Store is the initial domain object. // The Store creates some other domain objects. Store store = new Store(); Register register = store.getRegister(); ProcessSaleJFrame frame = new ProcessSaleJFrame( register ); ... } }
Hoa Sen University
261
Designing Store.create() Create: Store, Register, ProductCatalog,ProductSpecifications Associate: ProductCatalog with ProductSpecifications; Store with ProductCatalog; Store with Register; Register with ProductCatalog
Hoa Sen University
262
Designing Store.create() pass a reference to the ProductCatalog to the Register, so that it has permanent visibility to it
create
2: create(pc)
:Store
by Creator
:Register
create an empty collection object
1: create 1.1: create pc: ProductCatalog
1.2.2*: put(id, pd)
1.2: loadProdSpecs() the * in sequence number indicates the message occurs in a repeating section
Hoa Sen University
descriptions: Map
1.2.1*: create(id, price, description) pd: ProductDescription
263
Monopoly game project Two system operations in the first iteration – Initialize Ignore at this state
– Play game Main focus
Hoa Sen University
264
Design playGame Choosing the Controller Class – Represents the overall “system”, “root object” MonopolyGame? *
– Represents a receiver or handler of all system events of a use case scenario PlayGameHandler? Hoa Sen University
265
Game-Loop algorithm Terminology turn – a player rolling the dice and moving the piece round – all the players taking one turn Game loop for N rounds for each player p p takes a turn
Hoa Sen University
266
Who is responsible for controlling the game loop Information needed
Who has this information
The current round count
No object has it yet, assigning this to the MonopolyGame object is justifiable
All players
MonopolyGame object
Hoa Sen University
267
Who takes a turn? When there are multiple partial information experts to choose from – Place the responsibility in the dominant information expert – If the first guideline does not apply, consider the coupling and cohesion impact of each and choose the best – Consider possible future evolution – Taking a turn might involve buying property, deposit money in bank.. Etc. A player should have all information regarding those activities Information Needed
Who has the information
Current location of the player
Player
Two die objects
MonopolyGame
All the squares
Board Hoa Sen University
268
Partial design diagrams
Hoa Sen University
269
Taking a turn refine Taking a turn involves – Calculating the face value of two die – Calculating the new square location – Moving the player’s piece from an old location to a new location
Who coordinate all this – Player
Visibility problem – Player must have references to all those objects
Hoa Sen University
270
Taking a turn
Hoa Sen University
271
Command-Query Separation Principle Style 1# 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 playGame
Hoa Sen University
273
Initialization and the start up use case
Hoa Sen University
274
Visibility between objects class Register { ... private ProductCatalog catalog; ... }
enterItem (itemID, quantity)
: Register
: ProductCatalog
desc = getProductDesc( itemID )
public void enterItem( itemID, qty ) { ... desc = catalog.getProductDesc(itemID) ... }
Hoa Sen University
275
What is visibility Ways in which A can have visibility into B: – Attribute Visibility B is an attribute of A – Parameter Visibility B is a parameter of a method of A – Local Visibility B is a (non-parameter) local object in a method of A – Global visibility B is in some way globally visible Hoa Sen University
276
Attribute Visibility
public void enterItem(itemID, qty) { ... desc = catalog.getProductDesc(itemID) ... }
class Register { ... private ProductCatalog catalog; ... }
enterItem (itemID, quantity)
: Register
: ProductCatalog
desc = getProductDesc( itemID )
Hoa Sen University
277
Parameter Visibility enterItem(id, qty)
:Register
2: makeLineItem(desc, qty)
:Sale
1: desc = getProductDesc(id) 2.1: create(desc, qty) :Product Catalog makeLineItem(ProductDescription desc, int qty) { ... sl = new SalesLineItem(desc, qty); ... }
Hoa Sen University
sl : SalesLineItem
278
Parameter to attribute visibility enterItem(id, qty)
:Register
2: makeLineItem(desc, qty)
:Sale
2: desc = getProductDesc(id) 2.1: create(desc, qty) :Product Catalog sl : SalesLineItem // initializing method (e.g., a Java constructor) SalesLineItem(ProductDescription desc, int qty) { ... description = desc; // parameter to attribute visibility ... }
Hoa Sen University
279
Local visibility Local visibility from A to B exists when B is declared as a local object with in a method of A – Create a new local instance and assign it to a local variable – Assign the returning object from a method invocation to a local variable Variable desc of type ProductionDescription is a local variable of enterItem method enterItem(id, qty) { ... // local visibility via assignment of returning object ProductDescription desc = catalog.getProductDes(id); ... }
enterItem (itemID, quantity)
: Register
Hoa Sen University
: ProductCatalog
desc = getProductDesc( itemID )
280
Global visibility Global visibility from A to B exists when B is global to A; Permanent visibility as it persists as long as A and B exist – Global variable – Singleton pattern
Hoa Sen University
281