OOAD With UML
OOAD With UML
OOAD With UML
Introduction
About you
Name? Company? What are you working on? Previous experience of OO? Previous experience of modelling? One thing you hope to gain from this course? Any hobbies or interests?
Clear View Training 2005 v2.2 3
Labs
Introduction
UML Principles
UP
Requirements
Analysis
Design
Implementation
Summary
Guiding principles
This course uses the Unified Software Development Process (UP) to define the activities of OO analysis and design The UP is the industry standard software engineering process for the UML
xref
Course materials
Handouts Labs Solutions
Notes
For easy reference, all slides in this course are cross referenced to sections in the course book "UML 2 and the Unified Process"
There is an example cross reference icon in the top left hand corner of this slide Note: you will receive a pre-release printout of the course book if you are taking this course prior to its publication
Clear View Training 2005 v2.2 6
Labs
This is a practical course, and there is a lot of laboratory work Our approach to this work is cooperative rather than competitive
Work together Ask each other for help Share ideas and experience If something brings you to a halt for more than 10 minutes, then ask for help
To provide a thorough understanding of OO analysis and design with UML To follow the process of OO analysis and design from requirements capture through to implementation using the Unified Software Engineering Process as the framework To have fun!
Conditions of satisfaction
You can read and understand UML diagrams You can produce UML models in the laboratory work You apply your knowledge effectively back at your workplace
Questions
You can ask questions at any time! Your participation is always valued
10
Summary
11
UML principles
12
1.2
What is UML?
Unifies past modelling techniques and experience Incorporates current best practice in software engineering UML is not a methodology!
1.3
UML history
Prehistory
Schlaer/ Mellor Booch Rumbaugh (OMT) Jacobson (Objectory) Coad/ Yourdon Fusion 1st unification attempt
OMT, Booch, CRC
UML 1.x
UML 2.0
1994
Booch & Rumbaugh (OMT) join Rational
1995
Jacobson (Objectory) joins Rational
1996
1997
UML becomes an industry standard
2003
2004
Greater consistency More precisely defined semantics New diagram types Backwards compatible
Clear View Training 2005 v2.2 14
1.4
UML future
generate
Code
deploy
15
1.5
Why "unified"?
historical methods and notations the development lifecycle application domains implementation languages and platforms development processes internal concepts
16
1.6
UML models systems as collections of objects that interact to deliver benefit to outside users Static structure
Dynamic behaviour
1.7
UML Structure
In this section we present an overview of the structure of the UML All the modelling elements mentioned here are discussed later, and in much more detail!
Building blocks
Common mechanisms
Clear View Training 2005 v2.2
Architecture
18
1.8
Things
Modelling elements Tie things together Views showing interesting collections of things Are views of the model
Relationships
Diagrams
19
1.8.1
Things
Grouping things
package
Annotational things
Notes
Some Information about a thing Clear View Training 2005 v2.2 20
1.8.2
Relationships
relationship dependency association UML syntax brief semantics The source element depends on the target element and may be affected by changes to it. dependency
aggregation
composition containment generalization realization
dependency
dependency dependency dependency dependency
Clear View Training 2005 v2.2 21
1.8.3
normal font indicates an actual type of diagram that you can create
Structure diagrams model the structure of the system (the static model) Behavior diagrams model the dynamic behavior of the system (the dynamic model) Each type of diagram gives a different type of view of the model
Clear View Training 2005 v2.2 22
1.8.3
heading
contents area
heading syntax: <kind> <name> <parameters> N.B. <kind> and <parameters> are optional
The heading specifies the kind of diagram, its name and any information (parameters) needed by elements in the diagram The frame may be implied by a diagram area in the UML tool
Clear View Training 2005 v2.2
implied frame
23
1.9
UML has four common mechanisms that apply consistently throughout the language:
24
1.9.1
Specifications
BankAccount icon or modeling element name accountNumber deposit() withdraw() calculateInterest()
semantic backplane
Class specification
Deposit
Behind every UML modelling element is a specification which provides a textual statement of the syntax and semantics of that element These specifications form the semantic backplane of the model
Clear View Training 2005 v2.2 25
1.9.2
Adornments
Every UML modelling element starts with a basic symbol to which can be added a number of adornments specific to that symbol We only show adornments to increase the clarity of the diagram or to highlight a specific feature of the model
Window
{author = Jim, status = tested}
Window
+size : Area=(100,100) #visibility : Boolean = false +defaultSize: Rectangle #maximumSize : Rectangle -xptr : XWindow* +create() +hide() +display( location : Point ) -attachXWindow( xwin : XWindow*)
26
1.9.3
Common divisions
A classifier is an abstraction, an instance is a concrete manifestation of that abstraction The most common form is class/object e.g. a classifier might be a BankAccount class, and an instance might be an object representing my bank account Generally instances have the same notation as classes, but the instance name is underlined
An interface declares a contract and an implementation represents a concrete realization of that contract
Clear View Training 2005 v2.2
Borrowable
LibraryItem 27
1.9.4
Extensibility mechanisms
constraint note { each Ticket has a unique id }
Constraints
Extends the semantics of an element by allowing us to add new rules about the element Written as { some constraint } A stereotype allows us to define a new UML modelling element based on an existing one We define the semantics of the stereotype ourselves Stereotypes add new elements to the UML metamodel Written as stereotypeName Allows us to add new, ad-hoc information to an elements specification Written as { tag1 = value1, tag2 = value2 }
Clear View Training 2005 v2.2 28
Stereotypes
Tagged values
1.9.4.2
entity Ticket
stereotype
preferred
icon
preferred
Scheduler
A stereotype introduces a new modelling element and so we must always define semantics for our stereotypes Each model element can have many stereotypes
Clear View Training 2005 v2.2 29
1.9.4.4
UML profiles
A profile customizes UML for a specific purposes A UML profile is a collection of stereotypes, tagged values and constraints
Stereotypes extend one of the UML metamodel elements (e.g. Class, Association)
Any element that gets the stereotype also gets the associated tagged values and constraints
Clear View Training 2005 v2.2 30
1.10
Architecture
vocabulary functionality system assembly configuration management
Design view
behaviour
Implementation view
1.11
Summary
architecture
32
33
2.2
The Unified Software Development Process is an industry standard software engineering process
It is commonly referred to as the "Unified Process" or UP It is the generic process for the UML It is free - described in "The Unified Software Development Process", ISBN:0201571692" Use case (requirements) driven Risk driven Architecture centric Iterative and incremental
UP is:
UP is a generic software engineering process. It has to be customised (instantiated) for your project
In house standards, document templates, tools, databases, lifecycle modifications, RUP is a product marketed and owned by Rational Corporation RUP also has to be instantiated for your project
Clear View Training 2005 v2.2 34
2.3
UP history
Ericsson Approach Specification & Description Language
Objectory
Rational Approach
RUP 2001
Prehistory
1967
1976
1987
1995
1997
1998
1999
2001
2004
35
2.7
Iterations
Iterations are the key to the UP Each iteration is like a mini-project including:
Planning Analysis and design Integration and test An internal or external release
We arrive at a final product release through a sequence of iterations Iterations can overlap - this allows parallel development and flexible working in large teams
2.7.1
Iteration workflows
Each iteration may contain all of the core workflows but with a different emphasis depending on where the iteration is in the lifecycle
Requirements
Analysis
Design
Implementation
Test
An iteration
Planning
Project specific
Assessment
other workflows
Clear View Training 2005 v2.2 37
2.7.2
Baselines
Each iteration generates a baseline A baseline is a set of reviewed and approved artefacts that:
Provide an agreed basis for further review and development Can be changed only through formal procedures such as configuration and change management
An increment is the difference between the baseline generated by one iteration and the baseline generated by the next iteration
2.8
UP Structure
Milestone
Life-cycle Objectives Life-cycle Architecture Initial Operational Capability Product Release
Phase
Iterations
5 Core Workflows
Inception
Iter 1
Elaboration
Iter 2 Iter 3
Construction
Iter 4 Iter 5
Transition
Iter 6
R A D
I T
The exact number of iterations per phase depends on the size of the project! e.g. one iteration per phase for small projects
Clear View Training 2005 v2.2 39
2.9
This figure is the key to understanding UP! For each phase we will consider:
Requirements
Inception
Elaboration
Construction
Transition
The focus in terms of the core workflows The goal for the phase The milestone at the end of the phase
Design
Implementation
2.9.2
Inception
Requirements establish business case and scope. Capture core requirements Analysis establish feasibility
A D I
Inception Elaboration
Construction
Transition
Focus Goals
2.9.3
Inception - milestone
System scope has been defined Key requirements for the system have been captured. These have been defined and agreed with the stakeholders An architectural vision exists. This is just a sketch at this stage A Risk Assessment A Business Case Project feasibility is confirmed The stakeholders agree on the objectives of the project
Clear View Training 2005 v2.2 42
2.9.4
Elaboration
Requirements refine system scope and requirements Analysis establish what to build Design create a stable architectural baseline
Inception Elaboration
R A D
Construction
Transition
Focus Goals
Implementation build the architectural baseline Test test the architectural baseline Create an executable architectural baseline Refine Risk Assessment and define quality attributes (defect rates etc.) Capture use cases to 80% of the functional requirements Create a detailed plan for the construction phase Formulate a bid which includes resources, time, equipment, staff, cost Clear View Training 2005 v2.2 43
2.9.6
Elaboration - milestone
A resilient, robust executable architectural baseline has been created The Risk Assessment has been updated A project plan has been created to enable a realistic bid to be formulated The business case has been verified against the plan The stakeholders agree to continue
Clear View Training 2005 v2.2 44
2.9.7
Construction
R A
Requirements uncover any requirements that had been missed Analysis finish the analysis model Design finish the design model
Inception Elaboration Construction
Transition
Focus Goals
Implementation build the Initial Operational Capability Test test the Initial Operational Capability Complete use case identification, description and realization Finish analysis, design, implementation and test Maintain the integrity of the system architecture Revise the Risk Assessment
45
2.9.9
Construction - milestone
46
2.9.10
Transition
D
Requirements not applicable Analysis not applicable Design modify the design if problems emerge in beta testing Implementation tailor the software for the user site. Fix bugs uncovered in beta testing Test perform beta testing and acceptance testing at the user site Correct defects Prepare the user site for the new software and tailor the software to operate at the user site Modify software if unforeseen problems arise Create user manuals and other documentation Provide customer consultancy Conduct post project review Clear View Training 2005 v2.2 47
Inception Elaboration Construction
Transition
Focus Goals
2.9.12
Transition milestone
Beta testing, acceptance testing and defect repair are finished The product is released into the user community
48
2.10
Summary
UP is a risk and use case driven, architecture centric, iterative and incremental software development process UP has four phases:
49
Requirements - introduction
Requirements part 1
50
3.2
Requirements - purpose
The purpose of the requirements workflow is to create a high-level specification of what should be implemented We interview the stakeholders to find out what they need the system to do for them their requirements
Inception
Elaboration
Construction
Transition
51
3.3
Requirements - metamodel
Functional requirements
Requirements model
Non-functional requirements Software requirements specification package anchor icon P1 P3
P2
52
3.4
Requirements - workflow
Find actors and use cases System Analyst Structure the use case model
Architect
53
3.4
We add
find functional requirements Requirements Engineer find non-functional requirements prioritise requirements
Architect
In order to adopt a rigorous approach to requirements we need to extend the basic UP workflow with functional and non-functional requirements elicitation and requirements traceability
Clear View Training 2005 v2.2 54
3.5
3.6
What behaviour the system should offer A specific property of the system A constraint on the system The beginning of the OO software construction process it is a statement of the system requirements for all stakeholders Organises related requirements into sections Requirements model comprising functional and non-functional requirements Use case model comprising actors and use cases
Clear View Training 2005 v2.2 56
3.6.2
Writing requirements
<id> The <system> shall <function>
unique identifier name of system keyword function to be performed
e.g. "32 The ATM system shall validate the PIN number."
We recommend the uniform sentence structure above "The ATM system shall provide a facility for authenticating the identity of a system user"
3.7
Everyone filters information to create their own particular model of the world. Noam Chomsky described this as three processes:
Deletion information is filtered out Distortion information is modified by the related mechanisms of creation and hallucination Generalisation the creation of rules, beliefs and principles about truth and falsehood
These filters shape natural language and so we may need to work to recover filtered information
Clear View Training 2005 v2.2 58
3.8
Summary
We have had a brief overview of the three filters which people use to construct their model of the world
59
60
4.2
Use case modelling is a form of requirements engineering Use case modelling proceeds as follows:
It lets us identify the system boundary, who or what uses the system, and what functions the system should offer
Clear View Training 2005 v2.2 61
4.3
System Analyst
Supplementary Requirements
Project Glossary 62
4.3.1
The subject
subject SystemName
Where the boundary of the system lies Who or what uses the system What functions the system should offer to its users Subject the edge of the system
Actors who or what uses the system Use Cases things actors do with the system Relationships - between actors and use cases
63
4.3.2
Actors identify who or what uses the system and so indicate where the system boundary lies
Actors are external to the system An Actor specifies a role that some external entity adopts when interacting with the system
Customer
Customer Clear View Training 2005 v2.2 64
actor
4.3.2.1
Identifying Actors
Who or what uses the system? What roles do they play in the interaction? Who installs the system? Who starts and shuts down the system? Who maintains the system? What other systems use this system? Who gets and provides information to the system? Does anything happen at a fixed time?
Time Clear View Training 2005 v2.2 65
4.3.3
A use case is something an actor needs the system to do. It is a case of use of the system by a specific actor Use cases are always started by an actor
The primary actor triggers the use case Zero or more secondary actors interact with the use case in some way
Use cases are always written from the point of view of the actors
PlaceOrder
GetStatusOnOrder
66
4.3.3.1
Start with the list of actors that interact with the system When identifying use cases ask:
What functions will a specific actor want from the system? Does the system store and retrieve information? If so, which actors trigger this behaviour? Are any actors notified when the system changes state? Are there any external events that affect the system? What notifies the system about those events?
67
4.3.3.2
subject name
system boundary
Cancel Order
actor
use case
Dispatcher
68
4.3.4
Project Glossary
Term1 Definition Synonyms Homonyms
Term2
Term3
In any business domain there is always a certain amount of jargon. Its important to capture the language of the domain in a project glossary The aim of the glossary is to define key terms and to resolve synonyms and homonyms You are building a vocabulary that you can use to discuss the system with the stakeholders
69
4.4
Supplementary requirements
4.5
71
4.5.5
Preconditions and postconditions are constraints Preconditions constrain the state of the system before the use case can start Postconditions constrain the state of the system after the use case has executed If there are no preconditions or postconditions write "None" under the heading
Place Order
Preconditions: 1. A valid user has logged on to the system
Postconditions: 1. The order has been marked confirmed and is saved by the system
72
4.5.6
Main flow
<number> The <something> <some action>
The flow of events lists the steps in a use case It always begins by an actor doing something
A good way to start a flow of events is: 1) The use case starts when an <actor> <function> Declarative Numbered, Time ordered
The main flow is always the happy day or perfect world scenario
Everything goes as expected and desired, and there are no errors, deviations, interrupts, or branches Alternatives can be shown by branching or by listing under Alternative flows (see later)
Clear View Training 2005 v2.2 73
4.5.6.2
Use case: ManageBasket ID: 2 Brief description: The Customer changes the quantity of an item in the basket. Primary actors: Customer Secondary actors: None. Preconditions: 1. The shopping basket contents are visible. Main flow: 1. The use case starts when the Customer selects an item in the basket. 2. If the Customer selects "delete item" 2.1 The system removes the item from the basket. 3. If the Customer types in a new quantity 3.1 The system updates the quantity of the item in the basket. Postconditions: None. Alternative flows: None.
Use indentation and numbering to indicate the conditional part of the flow Use else to indicate what happens if the condition is false (see next slide)
74
4.5.6.4
We can use the keyword For to indicate the start of a repetition within the flow of events The iteration expression immediately after For statement indicates the number of repetitions of the indented text beneath the For statement.
ID: 3 Brief description: The system finds some products based on Customer search criteria and displays them to the Customer. Actors: Customer Preconditions: None. Main flow: 1. The use case starts when the Customer selects "find product". 2. The system asks the Customer for search criteria. 3. The Customer enters the requested criteria. 4. The system searches for products that match the Customer's criteria. 5. If the system finds some matching products then 5.1 For each product found 5.1.1. The system displays a thumbnail sketch of the product. 5.1.2. The system displays a summary of the product details. 5.1.3. The system displays the product price. 6. Else 6.1. The system tells the Customer that no matching products could be found. Postconditions: None. Alternative flows: None.
75
4.5.6.5
We can use the keyword while to indicate that something repeats while some Boolean condition is true
Use case: FindProduct ID: 3 Brief description: The system finds some products based on Customer search criteria and displays them to the Customer. Primary actors: Customer Secondary actors: None Preconditions: None. Main flow: 1. The use case starts when the Customer selects "find product". 2. The system asks the Customer for search criteria. 3. The Customer enters the requested criteria. 4. The system searches for products that match the Customer's criteria. 5. If the system finds some matching products then 5.1 For each product found 5.1.1. The system displays a thumbnail sketch of the product. 5.1.2. The system displays a summary of the product details. 5.1.3. The system displays the product price. 6. Else 6.1. The system tells the Customer that no matching products could be found. Postconditions: None. Alternative flows: None.
76
4.5.7
We may specify one or more alternative flows through the flow of events:
Use case
Alternative flows capture errors, branches, and interrupts Alternative flows never return to the main flow alternative flows
Pick the most important alternative flows and document those. If there are groups of similar alternative flows - document one member of the group as an exemplar and (if necessary) add notes to this explaining how the others differ from it.
main flow
4.5.7
List the names of the alternative flows at the end of the use case Find alternative flows by examining each step in the main flow and looking for:
ID: 5 Brief description: The system creates a new account for the Customer. Primary actors: Customer Secondary actors: None. Preconditions: None. Main flow: 1. The use case begins when the Customer selects "create new customer account". 2. While the Customer details are invalid 2.1. The system asks the Customer to enter his or her details comprising email address, password and password again for confirmation. 2.2 The system validates the Customer details. 3. The system creates a new account for the Customer. Postconditions: 1. A new account has been created for the Customer. Alternative flows: InvalidEmailAddress InvalidPassword Cancel
alternative flows
78
4.5.7
always indicate how the alternative flow begins. In this case it starts after step 2.2 in the main flow
Alternative flow: 1. The alternative flow begins after step 2.2. of the main flow. 2. The system informs the Customer that he or she entered an invalid email address. Postconditions: None.
The alternative flow may be triggered instead of the main flow - started by an actor The alternative flow may be triggered after a particular step in the main flow - after The alternative flow may be triggered at any time during the main flow - at any time
Clear View Training 2005 v2.2 79
4.6
Requirements tracing
Given that we can capture functional requirements in a requirements model and in a use case model we need some way of relating the two There is a many-to-many relationship between requirements and use cases:
One use case covers many individual functional requirements One functional requirement may be realised by many use cases With UML tagged values, we can assign numbered requirements to use cases We can capture use case names in our Requirements Database
80
4.7
Use cases describe system behaviour from the point of view of one or more actors. They are the best choice when:
The system is dominated by functional requirements The system has many types of user to which it delivers different functionality The system has many interfaces
Use cases are designed to capture functional requirements. They are a poor choice when:
The system is dominated by non-functional requirements The system has few users The system has few interfaces
81
Summary
We have seen how to capture functional requirements with use cases We have looked at:
Use cases Actors Branching with if Repetition with for and while Alternative flows Requirements tracing
Clear View Training 2005 v2.2 82
83
5.1
More relationships
We have studied basic use case analysis, but there are relationships that we have still to explore:
Actor generalisation Use case generalisation include between use cases extend between use cases
84
5.2
The Customer and the Sales Agent actors are very similar They both interact with List products, Order products, Accept payment Additionally, the Sales Agent interacts with Calculate commission Our diagram is a mess can we simplify it?
Sales system
ListProducts
Customer
OrderProducts
AcceptPayment
CalculateCommission
SalesAgent
85
5.2
Actor generalisation
If two actors communicate with the same set of use cases in the same way, then we can express this as a generalisation to another (possibly abstract) actor The descendent actors inherit the roles and relationships to use cases held by the ancestor actor We can substitute a descendent actor anywhere the ancestor actor is expected. This is the
ListProducts OrderProducts
generalisation
AcceptPayment
CalculateCommission
Customer SalesAgent
descendents or children
substitutability principle
5.3
The ancestor use case must be a more general case of one or more descendant use cases Child use cases are more specific forms of their parent They can inherit, add and override features of their parent
Use case generalization semantics Sales system
Add
Yes
Override
No
FindProduct
Customer FindBook FindCD
Extension point
Precondition
Yes
Yes
Yes
Yes
No
Yes
Postcondition
Yes
Yes
Yes Yes
Yes
Yes Yes
Clear View Training 2005 v2.2
87
5.4
include
The client use case executes until the point of inclusion: include(SupplierUseCase)
client
Personnel System
stereotype include
Control passes to the supplier use case which executes When the supplier is finished, control passes back to the client use case which finishes execution Manager Client use cases are not complete without the included supplier use cases Supplier use cases may be complete use cases, or they may just specify a fragment of behaviour for inclusion elsewhere
ChangeEmployeeDetails
ViewEmployeeDetails
include
FindEmployeeDetails
Note:
include DeleteEmployeeDetails
supplier
dependency relationship
When use cases share common behaviour we can factor this out into a separate supplier use case and include it in the clients
Clear View Training 2005 v2.2 88
5.4
include example
Use case: ChangeEmployeeDetails ID: 1 Brief description: The Manager changes the employee details. Primary actors: Manager Seconday actors: None Preconditions: 1. The Manager is logged on to the system. Main flow: 1. include( FindEmployeeDetails ). 2. The system displays the employee details. 3. The Manager changes the employee details. Postconditions: 1. The employee details have been changed. Alternative flows: None. ID: 4 Brief description: The Manager finds the employee details. Primary actors: Manager Seconday actors: None Preconditions: 1. The Manager is logged on to the system. Main flow: 1. The Manager enters the employee's ID. 2. The system finds the employee details. Postconditions: 1. The system has found the employee details. Alternative flows: None. Use case: FindEmployeeDetails
89
5.5
extend
extend is a way of adding new behaviour into the base use case by inserting behaviour from one or more extension use cases
The base use case specifies one or more extension points in its flow of events
Librarian
Borrow book
The extension use case may contain several insertion segments The extend relationship may specify which of the base use case extension points it is extending
Find book
The client use case inserts behaviour into the base use case. The base use case provides extension points, but does not know about the extensions.
90
5.5
IssueFine
There is an extension point overdueBook just before step 4 of the flow of events Extension points are not numbered, as they are not part of the flow
Clear View Training 2005 v2.2 91
5.5.1
ID: 10
Brief description: Segment 1: The Librarian records and prints out a fine. Primary actors: Librarian
extension point: overdueBook extend the single insertion segment in IssueFine is inserted at the overdueBook insertion point in the ReturnBook use case
Secondary actors: None. Segment 1 preconditions: 1. The returned book is overdue. Segment 1 flow: 1. The Librarian enters details of the fine into the system. 2. The system prints out the fine. IssueFine Segment 1 postconditions: 1. The fine has been recorded in the system. 2. The system has printed out the fine.
Extension use cases have one or more insertion segments which are behaviour fragments that will be inserted at the specified extension points in the base use case
Clear View Training 2005 v2.2 92
5.5.2
the first segment in IssueFine is inserted at overdueBook and the second segment at payFine
If more than one extension point is specified in the extend relationship then the extension use case must have the same number of insertion segments
Segment 2 flow: 1. The Librarian accepts payment for the fine from the borrower. 2. The Librarian enters the paid fine in the system. 3. The system prints out a receipt for the paid fine. Segment 2 postconditions: 1. The fine is recorded as paid. 2. The system has printed a receipt for the fine.
93
5.5.3
Conditional extensions
ReturnBook
extension points overdueBook payFine
condition extend
extend
IssueWarning
IssueFine
Conditions are Boolean expressions The insertion is made if and only if the condition evaluates to true
Clear View Training 2005 v2.2 94
5.6
Summary
Use advanced features with discretion only where they simplify the model!
Clear View Training 2005 v2.2 95
Analysis - introduction
Analysis part 1
96
6.2
Analysis - purpose
Inception
Elaboration
Construction
Transition
This model should be a statement of what the system does not how it does it We can think of the analysis model as a first-cut or high level design model It is in the language of the business
6.3
Analysis - metamodel
Packages contain UML modelling elements and diagrams (we only show the elements here) Each element or diagram is owned by exactly one package
P3 P1
Analysis Model
P4
P2
analysis class
98
6.4
Workflow - Analysis
Analysis guidelines:
6.5
50 to 100 classes in the analysis model of a moderately complex system Only include classes which are part of the vocabulary of the problem domain Dont worry about classes which define how something is implemented we will address these in Design Focus on classes and associations Dont worry about class inheritance too much Keep it simple!!!
Component Engineer
Analyze a package 99
100
7.2
Objects consist of data and function packaged together in a reusable unit. Objects encapsulate data Every object is an instance of some class which defines the common set of features (attributes and operations) shared by all of its instances. Objects have:
Identity: Each object has its own unique identity and can be accessed by a
unique handle State: This is the actual data values stored in an object at any point in time Behaviour: The set of operations that an object can perform
101
7.2.1
Encapsulation
Data is hidden inside the object. The only way to access the data is via one of the operations This is encapsulation or data hiding and it is a very powerful idea. It leads to more robust software and reusable code.
attribute values
operations
deposit()
number = "1243"
withdraw()
An Account Object
Clear View Training 2005 v2.2 102
7.2.2
Messaging
In OO systems, objects send messages to each other over links These messages cause an object to invoke an operation
Bank Object
message
Account Object
withdraw( 150.00 )
the Bank object sends the message withdraw 150.00 to an Account object.
the Account object responds by invoking its withdraw operation. This operation decrements the account balance by 150.00.
103
7.3
variants
jimsAccount : Account
jimsAccount : Account accountNumber : String = "1234567" owner : String = "Jim Arlow" balance : double = 300.00 jimsAccount
: Account
an anonymous object
attribute name
attribute type
attribute value
All objects of a particular class have the same set of operations. They are not shown on the object diagram, they are shown on the class diagram (see later) Attribute types are often omitted to simplify the diagram Naming:
104
7.4
Every object is an instance of one class - the class describes the "type" of the object Classes allow us to model sets of objects that have the same set of features - a class acts as a template for objects:
The class determines the structure (set of features) of all objects of that class All objects of a class must have the same set of operations, must have the same attributes, but may have different attribute values
Classification is one of the most important ways we have of organising our view of the world class Think of classes as being like:
7.4
106
7.4.1
Objects are instances of classes UML defines instantiation as, The creation of new instances of model elements Most classes provide special operations called constructors to create instances of that class. These operations have class-scope i.e. they belong to the class itself rather than to objects of the class We will see instantiation used with other modelling elements later on
Account
class
withdraw() deposit()
objects
107
7.5
Window
{author = Jim, status = tested}
+size : Area=(100,100) #visibility : Boolean = false +defaultSize: Rectangle #maximumSize : Rectangle -xptr : XWindow* +create() +hide() +display( location : Point ) -attachXWindow( xwin : XWindow*)
initialisation values
Classes are named in UpperCamelCase Use descriptive names that are nouns or noun phrases Avoid abbreviations!
Clear View Training 2005 v2.2 108
7.5.2
Attribute compartment
visibility name : type [multiplicity] = initialValue
mandatory
Everything is optional except name initialValue is the value the attribute gets when objects of the class are instantiated Attributes are named in lowerCamelCase
Use descriptive names that are nouns or noun phrases Avoid abbreviations
Attributes may be prefixed with a stereotype and postfixed with a list of tagged values
Clear View Training 2005 v2.2 109
7.5.2.1
Visibility
Symbol Name + public Semantics Any element that can access the class can access any of its features with public visibility
# ~
private
protected package
Only operations within the class can access features with private visibility
Only operations within the class, or within children of the class, can access features with protected visibility Any element that is in the same package as the class, or in a nested subpackage, can access any of its features with package visibility
PersonDetails -name : String [2..*] -address : String [3] -emailAddress : String [0..1]
You may ignore visibility in analysis In design, attributes usually have private visibility (encapsulation)
Clear View Training 2005 v2.2 110
7.5.2.3
Multiplicity
[0..1] means an that the attribute may have the value null
PersonDetails -name : String [2..*] -address : String [3] -emailAddress : String [0..1]
name is composed of 2 or more Strings address is composed of 3 Strings emailAddress is composed of 1 String or null
multiplicity expression
111
7.5.3
Operation compartment
operation signature
Special symbols and abbreviations are avoided Operation names are usually a verb or verb phrase They can return multiple objects (see next slide)
Operations may be prefixed with a stereotype and postfixed with a list of tagged values
Clear View Training 2005 v2.2 112
7.5.3.1
Parameter direction
parameter direction in semantics the parameter is an input to the operation. It is not changed by the operation. This is the default
out
inout return
maxMin( in a: int, in b:int, return maxValue:int return minValue:int ) max, min = maxMin( 5, 10 )
Clear View Training 2005 v2.2 113
7.6
Scope
114
7.6.1
You cant invoke an instance scope operation unless you have an instance of the class available. You cant use an instance scope operation of a class to create objects of that class, as you could never create the first object
7.7
Object construction
How do we create instances of classes? Each class defines one or more class scope operations which are constructors. These operations create new instances of the class
BankAccount +create( aNumber : int ) BankAccount +BankAccount( aNumber : int ) Java/C++ standard
116
7.7.1
Each ClubMember object has its own copy of the attribute membershipNumber The numberOfMembers attribute exists only once and is shared by all instances of the ClubMember class Suppose that in the create operation we increment numberOfMembers:
ClubMember -membershipNumber : String -memberName : String -numberOfMembers : int = 0 +create( number : String, name : String ) +getMembershipNumber() : String +getMemberName() : String -incrementNumberOfMembers() +decrementNumberOfMembers() +getNumberOfMembers() : int
7.8
Summary
We have looked at objects and classes and examined the relationship between them We have explored the UML syntax for modelling classes including:
Attributes Operations Attributes and operations are normally instance scope We can use class scope operations for constructor and destructors Class scope attributes are shared by all objects of the class and are useful as counters
Clear View Training 2005 v2.2 118
119
8.2
Analysis class
Requirements model
120
8.3
All classes in the Analysis model should be Analysis classes Analysis classes have:
A very high level set of attributes. They indicate the attributes that the design classes might have. Operations that specify at a high level the key services that the class must offer. In Design, they will become actual, implementable, operations.
operations
8.3.2
Its name reflects its intent It is a crisp abstraction that models one specific element of the problem domain
It maps onto a clearly identifiable feature of the problem domain Cohesion is the degree to which a class models a single abstraction Cohesion is the degree to which the responsibilities of the class are semantically related Coupling is the degree to which one class depends on others 3 to 5 responsibilities per class Each class collaborates with others Beware many very small classes Beware few but very large classes Beware of functoids Beware of omnipotent classes Avoid deep inheritance trees
Rules of thumb:
122
8.4
Finding classes
8.4.1
8.4.2
Collaborators: Bank
things the class works with
Maintain balance
Class, Responsibilities and Collaborators Separate information collection from information analysis
Part 1: Brainstorm
8.4.4
Be careful with this one if the existing business process is very poor, then the paperwork that supports it might be irrelevant
Known interfaces to the outside world Conceptual entities that form a cohesive abstraction e.g. LoyaltyProgramme
Clear View Training 2005 v2.2 126
8.6
Summary
Weve looked at what constitutes a well-formed analysis class We have looked at two analysis techniques for finding analysis classes:
Noun verb analysis of use cases, requirements, glossary and other relevant documentation CRC analysis
127
Analysis - relationships
Analysis part 5
128
9.2
What is a relationship?
A relationship is a connection between modelling elements In this section well look at:
129
9.3
Links
Think of a link as a telephone line connecting you and a friend. You can send messages back and forth using this link
Objects send messages to each other via links Messages invoke operations
OO programming languages implement links as object references or pointers. These are unique handles that refer to specific objects
When an object has a reference to another object, we say that there is a link between the objects
Clear View Training 2005 v2.2 130
9.3.1
Object diagrams
Paths in UML diagrams (lines to you and me!) can be drawn as orthogonal, oblique or curved lines We can combine paths into a tree if each path has the same properties
chairperson
ila:Person
bookClub:Club object
secretary
erica:Person
link
member
naomi:Person
BookClub
chairperson
ila:Person
bookClub:Club
secretary
erica:Person
preferred
member
naomi:Person 131
9.4
Associations
association Club Person
instantiate
instantiate
chairman jim:Person
Associations are relationships between classes Associations between classes indicate that there are links between objects of those classes A link is an instantiation of an association just as an object is an instantiation of a class
Clear View Training 2005 v2.2 132
9.4.1
Association syntax
Company
employs
1
multiplicity
association name
Person
navigability
Company
employer 1
role names
employee *
Person
An association can have role names or an association name. Its bad style to have both. The black triangle indicates the direction in which the association name is read: Company employs many Person(s)
Clear View Training 2005 v2.2 133
9.4.2
Multiplicity
A Company employs many People
Company
employer 1
employee *
Person
Multiplicity is a constraint that specifies the number of objects that can participate in a relationship at any point in time If multiplicity is not explicitly stated in the model then it is undecided there is no default
multiplicity
Multiplicity exercise
How many
Company
1 employer
Employees can a Company have? Employers can a Person have? Owners can a BankAccount have? Operators can a BankAccount have? BankAccounts can a Person have? BankAccounts can a Person operate?
7 employee
Person
owner 1 1..* operator
0..*
0..*
BankAccount
135
9.4.2.1
Exercise
Model a computer file system. Here are the minimal facts you need:
The basic unit of storage is the file Files live in directories Directories can contain other directories
Use your own knowledge of a specific file system (e.g. Windows 95 or UNIX) to build a model
9.4.2.1
Reflexive associations
subdirectory 0..*
Directory
0..1 parent
0..*
File
reflexive association
Windows Command
My Documents
directories
files
137
9.4.2.2
A
0..1
0..* 0..*
0..*
a1:A
b1:B b1:A c1:A d1:A e1:B
c1:B
f1:B
d1:B
e1:A
f1:A
g1:A
a1:B
g1:B
an an association hierarchy, each object has zero or one object directly above it
in an association network, each object has zero or many objects directly above it
138
9.4.3
Navigability
Navigability indicates that it is possible to traverse from an object of the source class to objects of the target class
Navigable
source
target
Order
Product
navigability
Objects of the source class may reference objects of the target class using the role name
Not navigable
Even if there is no navigability it might still be possible to traverse the relationship via some indirect means. However the computational cost of the traversal might be very high
A A A
B B B
A to B is navigable B to A is navigable A to B is navigable B to A is not navigable A to B is navigable B to A is undefined A to B is undefined B to A is undefined 139
A
Clear View Training 2005 v2.2
9.2
Strict UML 2 navigability can clutter diagrams so the UML standard suggests three possible modeling idioms:
Show navigability explicitly on diagrams Omit all navigability from diagrams Omit crosses from diagrams
bi-directional associations have no arrows unidirectional associations have a single arrow you can't show associations that are not navigable in either direction (not useful anyway!)
standard practice
A A
B B
Clear View Training 2005 v2.2
9.4.4
Address
House
address:Address
House
address:Address attribute
If a navigable relationship has a role name, it is as though the source class has a pseudoattribute whose attribute name is the role name and whose attribute type is the target class Objects of the source class can refer to objects of the target class using this pseudo-attribute Use associations when:
The target class is an important part of the model The target class is a class that you have designed yourself and which must be shown on the model The target class is not an important part of the model e.g. a primitive type such as number, string etc. The target class is just an implementation detail such as a bought-in component or a library component e.g. Java.util.Vector (from the Java standard libraries) Clear View Training 2005 v2.2 141
9.4.5
Association classes
Company * employment * Person
Each Person object can work for many Company objects. Each Company object can employ many Person objects. When a Person object is employed by a Company object, the Person has a salary.
Not on the Person class - there is a different salary for each employment Not on the Company class - different Person objects have different salaries The salary is a property of the employment relationship itself
9.4.5
Job
association class salary:double
We model the association itself as an association class. One instance of this class exists for each link between a Person object and a Company object
Instances of the association class are links that have attributes and operations Can only use association classes when there is one unique link between two specific objects. This is because the identity of links is determined exclusively by the identities of the objects on the ends of the link
We can place the salary and any other attributes or operations which are really features of the association into this class
Clear View Training 2005 v2.2 143
9.4.5
Company
Person
Job
salary:double
If, however a particular Person can have multiple jobs with the same Company, then we must use a reified
Company
Job
salary:double
Person
association
144
9.4.6
Qualified associations
Qualified associations reduce an n to many association to an n to 1 association by specifying a unique object (or group of objects) from the set They are useful to show how we can look up or navigate to specific objects Qualifiers usually refer to an attribute on the target class
Club 1 qualifier
* Member memberId:String
145
9.6
Summary
146
Analysis - dependencies
Analysis part 6
147
9.5
What is a dependency?
"A dependency is a relationship between two elements where a change to one element (the supplier) may affect or supply information needed by the other element (the client)". In other words, the client depends in some way on the supplier
Dependency is really a catch-all that is used to model several different types of relationship. Weve already seen one type of dependency, the instantiate relationship Usage - the client uses some of the services made available by the supplier to implement its own behavior this is the most commonly used type of dependency Abstraction - a shift in the level of abstraction. The supplier is more abstract than the client Permission - the supplier grants some sort of permission for the client to access its contents this is a way for the supplier to control and limit access to its contents
Clear View Training 2005 v2.2 148
9.5.1
Usage dependencies
use - the client makes use of the supplier to implement its behaviour call - the client operation invokes the supplier operation parameter - the supplier is a parameter of the client operation send - the client sends the supplier (which must be a signal) to some unspecified target instantiate - the client is an instance of the supplier
Clear View Training 2005 v2.2 149
9.5.1.1
use - example
the stereotype is often omitted
A
foo( b : B ) bar() : B doSomething()
use
A use dependency is generated between class A and B when: 1) An operation of class A needs a parameter of class B
2) An operation of class A returns a value of class B 3) An operation of class A uses an object of class B somewhere in its implementation
Clear View Training 2005 v2.2 150
9.5.2
Abstraction dependencies
trace - the client and the supplier represent the same concept but at different points in development substitute - the client may be substituted for the supplier at runtime. The client and supplier must realize a common contract. Use in environments that don't support specialization/generalization refine - the client represents a fuller specification of the supplier derive - the client may be derived from the supplier. The client is logically redundant, but may appear for implementation reasons
Clear View Training 2005 v2.2 151
9.5.2.4
derive - example
BankAccount
1 0..*
Transaction
1
BankAccount
0..*
Transaction
1 1
derive
balance 1
Quantity
/balance 1
Quantity
BankAccount
/balance:Quantity
0..*
Transaction
1
1
Quantity
152
9.5.3
Permission dependencies
access
The public contents of the supplier package are accessible to the contents of the client package - items in the client package must use pathnames to refer to items in the supplier package
The public contents of the supplier package are added to the namespace of the client package - items in the client package can refer to items in the supplier package without using pathnames The client element has access to the supplier element despite the declared visibility of the supplier
Clear View Training 2005 v2.2 153
import
permit
9.6
Summary
Dependency
154
155
10.2
Generalisation
A relationship between a more general element and a more specific element The more specific element is entirely consistent with the more general element but contains more information An instance of the more specific element may be used where an instance of the more general element is expected Substitutability
Principle
Clear View Training 2005 v2.2 156
10.2.1
generalisation
Square
Circle
Triangle
157
10.3
Class inheritance
Shape
origin : Point = (0,0) width : int {>0} height : int {>0} draw( g : Graphics ) getArea() : int getBoundingArea() : int
Subclasses can add new features Subclasses can override superclass operations We can use a subclass instance anywhere a superclass instance is expected
Substitutability Principle
Square
{width = height}
Circle
radius: int = width/2
10.3.1
Overriding
Shape
draw( g : Graphics ) getArea() : int getBoundingArea() : int
Square
Circle
draw( g : Graphics ) getArea() : int
width x height
p x radius2
Subclasses often need to override superclass behaviour To override a superclass operation, a subclass must provide an operation with the same signature
The operation signature is the operation name, return type and types of all the parameters The names of the parameters dont count as part of the signature
Clear View Training 2005 v2.2 159
10.3.2
getBoundingArea() : int
because we dont know how to draw or calculate the area for a "shape"! Operations that lack an implementation are abstract operations A class with any abstract operations cant be instantiated and is therefore an abstract class
Clear View Training 2005 v2.2 160
10.3.3
Exercise
JaguarXJS
Truck
161
10.4
Polymorphism
A Canvas object has a collection of Shape objects where each Shape may be a Square or a Circle Canvas 1 shapes * abstract superclass
A polymorphic operation has many implementations Square and Circle provide implementations for the polymorphic operations Shape::draw() and
Shape
polymorphic operations
Shape::getArea()
All concrete subclasses of Shape must provide concrete draw() and getArea() operations because they are abstract in the superclass
getBoundingArea() : int
For draw() and getArea() we can treat all subclasses of Shape in a similar way - we have defined a contract for Shape subclasses
Square
Circle
concrete subclasses
162
10.4.1
What happens?
Each class of object has its own implementation of the draw() operation On receipt of the draw() message, each object invokes the draw() operation specified by its class We can say that each object "decides" how to interpret the draw() message based on its class
s1:Circle
s2:Square
s3:Circle
s4:Circle
163
10.4.1
BankAccount example
BankAccount
Bank
* withdraw()
deposit()
calculateInterest()
ShareAccount
withdraw() calculateInterest() deposit()
CheckingAccount
withdraw() calculateInterest()
DepositAccount
withdraw() calculateInterest()
We have overridden the deposit() operation even though it is not abstract. This is perfectly legal, and quite common, although it is generally considered to be bad style and should be avoided if possible
Clear View Training 2005 v2.2 164
10.6
Summary
Subclasses:
inherit all features from their parents including constraints and relationships may add new features, constraints and relationships may override superclass operations
165
Analysis - packages
Analysis part 8
166
11.2
Analysis packages
A package is a general purpose mechanism for organising model elements into groups
Group semantically related elements Define a semantic boundary in the model Provide units for parallel working and configuration management Each package defines an encapsulated namespace i.e. all names must be unique within the package Use components for physical grouping A hierarchy rooted in a top level package that can be stereotyped topLevel Use cases, analysis classes, use case realizations, analysis packages
Clear View Training 2005 v2.2 167
11.2
Package syntax
Membership Membership access see later! Membership public (exported) elements private element +ClubMembership +Benefits +MembershipRules +MemberDetails:Member -JoiningRules JoiningRules
MemberDetails
Member
ClubMembership
Benefits
Membership:MemberDetails
MembershipRules
standard UML 2 package stereotypes framework modelLibrary A package that contains model elements that specify a reusable architecture A package that contains elements that are intended to be reused by other packages Clear View Training 2005 v2.2 168
11.4
Nested packages
If an element is visible within a package then it is visible within all nested packages e.g. Benefits is visible within MemberDetails Show containment using nesting or the containment relationship Use access or import to merge the namespace of nested packages with the parent namespace
JoiningRules
ClubMembership MembershipRules
Benefits
Membership
MemberDetails
169
11.5
Package dependencies
dependency Supplier semantics Client An element in the client uses an element in the supplier in some way. The client depends on the supplier. Transitive. Public elements of the supplier namespace are added as public elements to the client namespace. Elements in the client can access all public elements in the supplier using unqualified names. Public elements of the supplier namespace are added as private elements to the client namespace. Elements in the client can access all public elements in the supplier using unqualified names. trace usually represents an historical development of one element into another more refined version. It is an extra-model relationship. Transitive.
use
Supplier
import
Client
merge
The client package merges the public contents of its supplier packages. This is a complex relationship only used for metamodeling - you can ignore it.
transitivity - if dependencies x and y are transitive, there is an implicit dependency between A and C Clear View Training 2005 v2.2 170
11.6
Package generalisation
The more specialised child packages inherit the public and protected elements in their parent package Child packages may override elements in the parent package. Both Hotels and CarHire packages override Product::Item Child packages may add new elements. Hotels adds Hotel and RoomType, CarHire adds Car
Product
parent +Price +Market +Item -MicroMarket
Hotels
+Product::Price +Product::Market +Item +Hotel +RoomType
CarHire
+Product::Price +Product::Market +Item +Car
children
171
11.7
Architectural analysis
application specific layer Sales Products
Account Management
Inventory Management
partitions
This involves organising the analysis classes into a set of cohesive packages The architecture should be layered and partitioned to separate concerns
Its useful to layer analysis models into application specific and application general layers
Coupling between packages should be minimised Each package should have the minimum number of public or protected elements
Clear View Training 2005 v2.2 172
11.7.1
These are often discovered as the model matures We can use the natural groupings in the use case model to help identify analysis packages:
One or more use cases that support a particular business process or actor Related use cases
Analysis classes that realise these groupings will often be part of the same analysis package Be careful, as it is common for use cases to cut across analysis packages!
One class may realise several use cases that are allocated to different packages
Clear View Training 2005 v2.2 173
11.7.2
A cohesive group of closely related classes or a class hierarchy and supporting classes Minimise dependencies between packages Localise business processes in packages where possible Minimise nesting of packages Dont worry about dependency stereotypes Dont worry about package generalisation Refine package structure as analysis progresses 5 to 10 classes per package Avoid cyclic dependencies!
C A
merge
split
B
174
11.8
Summary
Packages are the UML way of grouping modeling elements There are dependency and generalisation relationships between packages The package structure of the analysis model defines the logical system architecture
175
176
12.2
Analysis class
Requirements model
Use case model Use case realization Architecture description Clear View Training 2005 v2.2 177
12.3
Place Order
trace dependency
Place Order
parts of the model that show how analysis classes collaborate together to realise the behaviour specified by the use case they model how the use case is realised by the analysis classes we have identified they form an implicit part of the backplane of the model they can be drawn as a stereotyped collaboration
Clear View Training 2005 v2.2 178
12.4
UC realization - elements
These show relationships between the analysis classes that interact to realise the UC These show collaborations between specific objects that realise the UC. They are snapshots of the running system UC realization may well uncover new requirements specific to the use case. These must be captured We may discover new information during realization that means that we have to update the original UC
Interaction diagrams
Special requirements
179
12.5
Interactions
Interactions are units of behavior of a context classifier In use case realization, the context classifier is a use case
The interaction shows how the behavior specified by the use case is realized by instances of analysis classes
Lifelines participants in the interaction Messages communications between lifelines
180
12.6
Lifelines
jimsAccount [ id = "1234" ] : Account
name
selector
type
Lifelines have:
They must be uniquely identifiable within an interaction by name, type or both The lifeline has the same icon as the classifier that it represents
The lifeline jimsAccount represents an instance of the Account class The selector [ id = "1234" ] selects a specific Account instance with the id "1234"
Clear View Training 2005 v2.2 181
12.7
Messages
sender
calling an operation synchronously the sender waits for the receiver to complete
asynchronous calling an operation asynchronously, sending a signal send the sender does not wait for the receiver to complete message return returning from a synchronous operation call the receiver returns focus of control to the sender the sender creates the target
:A
creation
the sender destroys the receiver the message is sent from outside the scope of the interaction the message fails to reach its destination Clear View Training 2005 v2.2 182
12.8
Interaction diagrams
Sequence diagrams
Emphasize time-ordered sequence of message sends Show interactions arranged in a time sequence Are the richest and most expressive interaction diagram Do not show object relationships explicitly - these can be inferred from message sends
Emphasize the structural relationships between lifelines Use communication diagrams to make object relationships explicit Show how complex behavior is realized by a set of simpler interactions Emphasize the real-time aspects of an interaction
Clear View Training 2005 v2.2 183
Communication diagrams
Timing diagrams
12.9
addCourse( "UML" )
create
uml:Course
Activations indicate when a lifeline has focus of control - they are often omitted from sequence diagrams
Clear View Training 2005 v2.2 184
12.9
uml:Course
deleteCourse( "UML" )
Object deletion is shown by terminating the lifeline's tail at the point of deletion by a large X Clear View Training 2005 v2.2 185
12.9.3
raiseOrder() create state invariant label constraint A acceptPayment() acceptPayment() deliver() {B A <= 28 days} delivered B deliver() unpaid paid :Order
186
12.10
Combined fragments
:A
operator
:B
a( )
:C
combined fragment
b( )
operands guard conditions must be placed above the first event occurrence
Sequence diagrams may be divided into areas called combined fragments Combined fragments have one or more operands Operators determine how the operands are executed Guard conditions determine whether operands execute. Execution occurs if the guard condition evaluates to true
A single condition may apply to all operands OR Each operand may be protected by its own condition
Clear View Training 2005 v2.2 187
12.10
Common operators
operator opt alt loop long name Option Alternatives Loop semantics There is a single operand that executes if the condition is true (like if then) The operand whose condition is true is executed. The keyword else may be used in place of a Boolean expression (like select case) This has a special syntax: loop min, max [condition] Iterate min times and then up to max times while condition is true The combined fragment is executed rather than the rest of the enclosing interaction The combined fragment refers to another interaction
break ref
break Reference
ref
findStudent(name):Student
ref has a single operand that is a reference to another interaction. This is an interaction occurrence.
188
12.10
12.10.1
opt semantics:
single operand that executes if the condition is true two or more operands each protected by its own condition an operand executes if its condition is true use else to indicate the operand that executes if none of the conditions are true
alt semantics:
:A
opt [condition]
:B
do this if condition is true
:C
:D
alt
190
12.10.2
loop semantics:
Loop min times, then loop (max min) times while condition is true A loop without min, max or condition is an infinite loop If only min is specified then max = min condition can be
sd examples of loop
loop syntax
:A
loop min, max [condition] loop while guard condition is true loop [condition] do something break do something
:B
Break specifies what happens when the loop is broken out of:
The break fragment executes The rest of the loop after the break does not execute
The break fragment is outside the loop and so should overlap it as shown
191
12.10.2
loop idioms
type of loop infinite loop for i = 1 to n {body} while( booleanExpression ) {body} repeat {body} while( booleanExpression ) forEach object in set {body} semantics keep looping forever repeat ( n ) times repeat while booleanExpression is true execute once then repeat while booleanExpression is true Execute the loop once for each object in a set loop expression loop * loop n loop [ booleanExpression ] loop 1, * [booleanExpression]
use a for loop with an index (see later) use the idiom [for each object in ObjectType] (e.g. [for each student in :Student] )
Clear View Training 2005 v2.2 192
12.11
Communication diagrams emphasize the structural aspects of an interaction - how lifelines connect together
Compared to sequence diagrams they are semantically weak Object diagrams are a special case of communication diagrams
sd AddCourses
sequence number message lifeline
uml:Course
:Registrar
link
2.1: create mda:Course Clear View Training 2005 v2.2 object creation message 193
12.11.1
Iteration
Iteration is shown by using the iteration specifier (*), and an optional iteration
clause
There is no prescribed UML syntax for iteration clauses Use code or pseudo code
:RegistrationManager
:Registrar
1.1.1: print()
[i]:Course
To show that messages are sent in parallel use the parallel iteration specifier, *//
Clear View Training 2005 v2.2 194
12.11.2
Branching
return value from message sd register student for course 1.1: student = findStudent( "Jim" ) 1.2: course = findCourse( "UML" )
course:Course
condition
There is no prescribed UML syntax for guard conditions! In the example above, we use the variable found. This is true if both the student and the course are found, otherwise it is false
Clear View Training 2005 v2.2 195
12.12
Summary
In this section we have looked at use case realization using interaction diagrams There are four types of interaction diagram:
Sequence diagrams emphasize time-ordered sequence of message sends Communication diagrams emphasize the structural relationships between lifelines Interaction overview diagrams show how complex behavior is realized by a set of simpler interactions Timing diagrams emphasize the real-time aspects of an interaction
We have looked at sequence diagrams and communication diagrams in this section - we will look at the other types of diagram later
Clear View Training 2005 v2.2 196
197
13.2
Interaction occurrences
sd I1
interaction
sd I2
:A
m1
:B
:A
interaction occurrence
:B
n1 n2
:C
ref
I1
n3
All lifelines in the interaction occurrence must also be in the including interaction Be very aware of where the interaction occurrence leaves the focus of control!
13.2.1
Parameters
interaction parameters
sd I3(p1:String):String
:A m1(p1) :B
attribute a of class A gets the return value of I3
sd I4
:A n1 :B n2 :C
ref
This allows specific values to be supplied to the interaction in each of its occurrences Specify parameters using operation syntax Values for the parameters are supplied in the interaction occurrences You can show a specific return value as a value return e.g. A:a = I3( "value" ):"ret"
13.2.2
Gates
sd I1
interaction
sd I2
D
m0 r m1
A
n1 m0 r ref n3
B
n2 I1
Gates are inputs and outputs of interactions (and combined fragments see next slide)
Provide connection points that relate messages inside an occurrence or fragment to messages outside it
13.3
Continuations
Continuations allow an interaction fragment to terminate in such a way that it can be continued by another fragment
get course option handle course option
:Registrar
:RegistrationUI
:Registrar ref
:RegistrationUI
:RegistrationManager
addCourse( name )
continuation
removeCourse
removeCourse( name )
findCourse
13.4
Summary
In this section we have looked at: Interaction occurrences Parameters Gates Continuations
202
203
14.2
Activity diagrams
Activity diagrams are "OO flowcharts"! They allow us to model a process as a collection of nodes and edges between those nodes Use activity diagrams to model the behavior of:
use cases classes interfaces components collaborations operations and methods business processes
Clear View Training 2005 v2.2 204
14.4
Activities
Activities are networks of nodes connected by edges There are three categories of node:
Action nodes - represent discrete units of work that are atomic within the activity Control nodes - control the flow through the activity Object nodes - represent the flow of objects around the activity
Edges represent flow through the activity There are two categories of edge:
Control flows - represent the flow of control through the activity Object flows - represent the flow of objects through the activity
205
14.4
Send letter
Activities usually start in an initial node and terminate in a final node Activities can have preconditions and postconditions When an action node finishes, it emits a token that may traverse an edge to trigger the next action
precondition: know topic for letter postcondition: letter sent to address initial node action node edge
Write letter
Address letter
transition
control flow
Post letter
final node
206
14.5
Token an object, some data or a focus of control Imagine tokens flowing around the activity diagram
The source node, edge and target node may all have constraints controlling the movement of tokens All constraints must be satisfied before the token can make the traversal It has tokens on all of its input edges AND these tokens satisfy predefined conditions (see later)
Write letter
localPrecondition address is known
Address letter
localPostcondition letter is addressed
When a node starts to execute it takes tokens off its input edges When a node has finished executing it offers tokens on its output edges
Post letter
207
14.6
Activity partitions
Course production
Location Zurich Marketing Scheduling
Partitions can refer to many different things e.g. business organisations, classes, components and so on If partitions cant be shown clearly using parallel lines, put their name in brackets directly above the name of the activities
(London::Marketing) Market product (p1, p2) SomeAction
Develop course
Schedule course
Book trainers
activity partition
Market course
Book rooms
nested partitions
208
14.7
Action nodes
input token
action node does not execute
There is a token simultaneously on each input edge The input tokens satisfy all preconditions specified by the node Perform a logical AND on their input edges when they begin to execute Perform an implicit fork on their output edges when they have finished executing
Action node
Action node
Action nodes:
Action node
output token
209
14.7
It may accept input parameters to create the signal Accept event action - waits for events detected by its owning object and offers the event on its output edge. Is enabled when it gets a token on its input edge. If there is no input edge it starts when its containing activity starts and is always enabled. Accept time event action - waits for a set amount of time. Generates time events according to it's time expression. time expression Clear View Training 2005 v2.2 210
wait 30 mins
14.7.1
The most common type of node Call action nodes may invoke:
Raise Order
call a behavior
operation name class name (optional) node name operation name (optional) programmin g language (e.g. Python) 211
The keyword 'self' refers to the context of the activity that owns the action
call an operation
if self.balance <= 0: self.status = 'INCREDIT' else self.status = 'OVERDRAWN' Clear View Training 2005 v2.2
14.8
Control nodes
control node syntax control node semantics
Initial node indicates where the flow starts when an activity is invoked Activity final node terminates an activity Flow final node terminates a specific flow within an activity. The other flows are unaffected
decisionInput decision condition
Decision node guard conditions on the output edges select one of them for traversal May optionally have inputs defined by a decisionInput Merge node selects one of its input edges Fork node splits the flow into multiple concurrent flows
{join spec}
Join node synchronizes multiple concurrent flows May optionally have a join specification to modify its semantics
212
14.8.2
A decision node is a control node that has one input edge and two or more alternate output edges
Each edge out of the decision is protected by a guard condition guard conditions must be mutually exclusive The edge can be taken if and only if the guard condition evaluates to true The keyword else specifies the path that is taken if none of the guard conditions are true
decision node
Open mail
Bin mail
It has two or more input edges and exactly one output edge
Clear View Training 2005 v2.2
merge node
213
14.8.3
Product process
Tokens on the single input edge are replicated at the multiple output edges
fork node
Joins have two or more incoming edges and exactly one outgoing edge A token is offered on the outgoing edge when there are tokens on all the incoming edges i.e. when the concurrent flows of work have all finished
Market product
Manufacture product
join node
Sell product
214
14.9
Object nodes
If no classifier is specified, then the object node can hold any type of instance
object node
The upper bound defines the maximum number of tokens (infinity is the default)
object node for signal
FIFO first in, first out (the default) LIFI last in, first out Modeler defined a selection criterion is specified for the object node
Clear View Training 2005 v2.2
OrderEvent
215
14.9
Order
Order
{upperBound = 12}
Order
{ordering = LIFO}
last Order object in is the first out (FIFO is the default) sets of Order objects may be available Order objects raised in December may be available select Order objects in the open state
216
Set of Order
selection monthRaised = "Dec"
14.9.3
Input parameters have one or more output object flows into the activity Output parameters have one or more input object flows out of the activity
14.10
Pins
LogOn
UserName[valid] GetUserName Authenticate User GetPassword Password[valid] exception pin pin LogError LogOnException
Pins are object nodes for inputs to, and outputs from, actions
Same syntax as object nodes Input pins have exactly one input edge Output pins have exactly one output edge Exception pins are marked with an equilateral triangle Streaming pins are filled in black or marked with {stream}
Clear View Training 2005 v2.2
{stream}
Summary
We have seen how we can use activity diagrams to model flows of activities using:
Activities
Connectors
Call action node Send signal/accept event action node Accept time event action node decision and merge fork and join input and output parameters pins
Clear View Training 2005 v2.2 219
Control nodes
Object nodes
220
15.3
Cancel
interrupting edge
Interruptible activity regions may be interrupted when a token traverses an interrupting edge
alternative notation
221
15.4
Exception handlers
Create set of Students FileName Read Student file exception handler action Handle file error protected java.io.IOException node exception type
When the exception object is raised in the protected node, flow is directed along an interrupting edge to the exception handler body
Clear View Training 2005 v2.2 222
15.5
Expansion nodes
Expansion node an object node that represents a collection of objects flowing into or out of an expansion
mode
region
Output collections must correspond to input collections in collection type and object type!
Grade Student
The expansion region is executed once per input element according to the keyword:
iterative process sequentially parallel process in parallel stream process a stream of input objects
Set of Student
Expansion regions containing a single action - place the expansion node directly on the action
15.6
Validate card
CardDetails Enter PIN
The accept event action asynchronously accepts event triggers which may be signals or other objects
SecurityEvent
signal
send signal
accept event
[!isAuthorized]
Not authorized
signal AuthorizationEvent
isAuthorized : Boolean
224
15.8
Input effect
input effect sendReceipt Receipt {timestamp} transformation Order.toReceipt() : Receipt Order [paid]
Output effect
selection
transformation
Order
sendReminder
225
15.9
A multicast object flow sends an object to multiple receivers A multireceive object flow receives an object from multiple receivers
Technical Group Identify need Request for Proposal Assess Proposals multireceive
Member
RFP
Proposal [Candidate]
15.10
Parameter sets
Authenticate User [password] Get UserName and Password Get UserName and Passphrase Get Card and PIN parameter set Authenticate
Password User [Authenticated]
UserName
[passphrase]
User
User [!Authenticated]
[card]
input condition: ( UserName AND Password ) XOR ( UserName AND Passphrase ) XOR ( Card AND PIN ) output: ( User [Authenticated] ) XOR ( User [!Authenticated] )
Parameter sets provide alternative sets of input pins and output pins to an action
Only one input set and one output set may be chosen (XOR)
Clear View Training 2005 v2.2 227
15.11
process Order
Order [new]
Central buffer nodes accept multiple upstream object flows They hold the objects until downstream nodes are ready for them
Clear View Training 2005 v2.2 228
15.12
Model the high level flow of control between interactions Show interactions and interaction occurrences Have activity diagram syntax
sd ref Logon
interaction occurrence
sd ref GetCourseOption
inline interaction
sd AddCourse
[exit]
229
15.13
Summary
In this section we have looked at some of the more advanced features of activity diagrams:
Interruptible activity regions Exception handlers Expansion nodes Advanced object flow Multicast and multireceive Parameter sets Central buffer nodes Interaction overview diagrams
Clear View Training 2005 v2.2 230
Design - introduction
Design part 1
231
16.2
Design - purpose
Decide how the system's functions are to be implemented Decide on strategic design issues such as persistence, distribution etc. Create policies to deal with tactical design issues
Inception
Elaboration
Construction
Transition
232
16.3
Subsystems are components that contain UML elements We create the design model from the analysis model by adding implementation details There is a historical trace relationship between the two models
physical model
Design Model
subsystem c1
I subsystem c2 trace c3
Analysis Model
conceptual model
Clear View Training 2005 v2.2 233
16.3.1
Design artefacts
Design model
0..*
Analysis package
trace
0..*
Design subsystem
Design class
interface Interface
Deployment model
Use case realization - analysis
trace
234
16.3.2
A design model may contain 10 to 100 times as many classes as the analysis model
The analysis model helps us to see the big picture without getting lost in implementation details It is a big system ( >200 design classes) It has a long expected lifespan It is a strategic system We are outsourcing construction of the system It is a small system It has a short lifespan It is not a strategic system
Clear View Training 2005 v2.2 235
16.4
Workflow - Design
Architectural design Architect
Component Engineer
Design a class
Design a subsystem
236
16.6
Summary
Design is the primary focus in the last part of the elaboration phase and the first half of the construction phase Purpose to decide how the system's functions are to be implemented artifacts:
Design classes Interfaces Design subsystems Use case realizations design Deployment model
Clear View Training 2005 v2.2 237
Design - classes
Design part 2
238
17.3
Design classes are classes whose specifications have been completed to such a degree that they can be implemented
Specifies an actual piece of code Remember - analysis classes arise from a consideration of the problem domain
only
A refinement of analysis classes to include implementation details One analysis class may become many design classes All attributes are completely specified including type, visibility and default values Analysis operations become fully specified operations (methods) with a return type and parameter list
Utility classes String, Date, Time etc. Middleware classes database access, comms etc. GUI classes Applet, Button etc.
Clear View Training 2005 v2.2 239
17.3
java.util
240
17.4
BankAccount
trace -name:String -number:String -balance:double = 0 +BankAccount(name:String, number:String) +deposit(m:double):void +withdraw(m:double):boolean +calculateInterest():double +getName():String +setName(n:String):void +getAddress():String +setAddress(a:String):void +getBalance():double +BankAccount(n:String,a:String,m:double)
constructor
A complete set of operations including parameter lists, return types, visibility, exceptions, set and get operations, constructors and destructors A complete set of attributes including types and default values
241
17.5
How do the users of your classes see them? Always look at your classes from their point of view!
MyClass
242
17.5.1
17.5.2
Completeness:
Users of the class will make assumptions from the class name about the set of operations that it should make available For example, a BankAccount class that provides a withdraw() operation will be expected to also provide a deposit() operation! A class should never surprise a user it should contain exactly the expected set of features, no more and no less Operations should be designed to offer a single primitive, atomic service A class should never offer multiple ways of doing the same thing:
Sufficiency:
Primitiveness:
The public members of a class define a "contract" between the class its clients
This is confusing to users of the class, leads to maintenance burdens and can create consistency problems
For example, a BankAccount class has a primitive operation to make a single deposit. It should not have an operation that makes two or more deposits as we can achieve the same effect by repeated application of the primitive operation
Clear View Training 2005 v2.2 243
17.5.3
17.5.4
High cohesion:
Each class should have a set of operations that support the intent of the class, no more and no less Each class should model a single abstract concept If a class needs to have many responsibilities, then some of these should be implemented by helper classes. The class then delegates to its helpers
A particular class should be associated with just enough other classes to allow it to realise its responsibilities Only associate classes if there is a true semantic link between them Never form an association just to reuse a fragment of code in another class! Use aggregation rather than inheritance (next slide)
Clear View Training 2005 v2.2
HotelBean
CarBean
HotelCarBean
Low coupling:
this example comes from a real system! Whats wrong with it?
244
17.6
Inheritance gives you fixed relationships between classes and objects You cant change the class of an object at runtime There is a fundamental semantic error here. Is an Employee just their job or does an Employee have a job?
Employee
Manager
Programmer
instantiate
john:Programmer
1.
2.
245
17.6.1
A better solution
Employee
0..*
0..*
Job
With this more flexible model, Employees can have more than one Job
instantiate
Manager
instantiate
Programmer
instantiate
:Manager john:Employee
:Programmer
17.6.2
Multiple inheritance
Sometimes a class may have more than one superclass The "is kind of" and substitutability principles must apply for all of the classifications Multiple inheritance is sometimes the most elegant way of modelling something. However:
Alarm
IActivate
Dialler
AutoDialler
Not all languages support it (e.g. Java) It can always be replaced by single inheritance and delegation
in this example the AutoDialler sounds an alarm and rings the police when triggered - it is logically both a kind of Alarm and a kind of Dialler
247
17.6.3
Interface the public operations of the base classes Implementation the attributes, relationships, protected and private operations of the base classes
An interface a set of public operations, attributes and relationships that have no implementation
Use inheritance when we want to inherit implementation. Use interface realization when we want to define a contract.
Clear View Training 2005 v2.2 248
17.7
Templates
Up to now, we have had to specify the types of all attributes, method returns and parameters. However, this can be a barrier to reuse Consider:
spot the difference!
BoundedIntArray
BoundedFloatArray
BoundedStringArray
size:int elements[]:int
addElement( e:int ):void getElement( i:int):int
size:int elements[]:float
addElement( e:float ):void getElement( i:int):float
size:int elements[]:String
addElement( e:String ):void getElement( i:int):String
etc.
249
17.7
Template syntax
template parameters
template
BoundedArray elements[size]:T addElement( e:T ):void getElement( i:int):T
T, size:int=10
default value
IntArray
elements[100]:int addElement( e:int ):void getElement( i:int):int StringArray
bind<T->int, size->100>
elements[10]:String
addElement( e:String ):void getElement( i:int):String
Template instantiation - the template parameters are bound to actual values to create new classes based on the template:
If the type of a parameter is not specified then the parameter defaults to being a classifier Parameter names are local to the template two templates do not have relationship to each other just because they use the same parameter names! Explicit binding is preferred as it allows named instantiations
Clear View Training 2005 v2.2
Templates and multiple inheritance should only be used in design models where those features are available in the target language:
language C# Java C++ Smalltalk templates Yes Yes Yes No multiple inheritance No No Yes No
Visual Basic
Python
No
No
No
Yes
251
17.8
Nested classes
Frame
anchor icon
MouseAdapter
HelloFrame
containment relationship
MouseMonitor
It is encapsulated inside the namespace of its containing class Nested classes tend to be design artifacts their containing class objects of that their containing class
Clear View Training 2005 v2.2 252
17.9
Summary
A refinement of analysis classes (i.e. the business domain) From the solution domain
Complete and sufficient Primitive operations High cohesion Low coupling Use inheritance for "is kind of" Use aggregation for "is role played by" Multiple inheritance should be used sparingly (mixins) Use interfaces rather than inheritance to define contracts
Use templates and nested classes only where the target language supports them
Clear View Training 2005 v2.2 253
254
18.2
Design relationships
refining associations to aggregation or composition relationships where appropriate implementing one-to-many associations implementing many-to-one associations implementing many-to-many associations implementing bidirectional associations implementing association classes navigability multiplicity on both ends
Clear View Training 2005 v2.2 255
18.3
A
{xor}
B
composition
trace
trace
Design
In analysis, we often use unrefined associations. In design, these can become aggregation or composition relationships We must also add navigability, multiplicity and role names
Clear View Training 2005 v2.2 256
18.3
Aggregation
Composition
Some objects are weakly related like a computer and its peripherals
Some objects are strongly related like a tree and its leaves
257
18.4
Aggregation
aggregation is a wholepart relationship
A Computer may be attached to 0 or more Printers At any one point in time a Printer is connected to 0 or 1 Computer Over time, many Computers may use a given Printer The Printer exists even if there are no Computers The Printer is independent of the Computer
Computer
whole or aggregate
0..1
0..*
Printer
part
aggregation
The aggregate can sometimes exist independently of the parts, sometimes not The parts can exist independently of the aggregate The aggregate is in some way incomplete if some of the parts are missing It is possible to have shared ownership of the parts by several aggregates
Clear View Training 2005 v2.2 258
18.4
Aggregation semantics
A B C
Aggregation (and composition) are transitive If C is a part of B and B is a part of A, then C is a part of A
reflexive aggregation
a:Product
cycles are NOT allowed
* Product
b:Product c:Product
Aggregation (and composition) are asymmetric An object can never be part of itself!
Clear View Training 2005 v2.2
d:Product
259
18.4
Aggregation hierarchy
HomeComputer
1 1 1 1 2
Mouse
Keyboard
CPU
Monitor
1
Speaker
connectedTo
1 1
1..*
RAM
FloppyDrive
HardDrive
CDRom
SoundCard
1
GraphicsCard
connectedTo
260
18.5
Composition
composition is a strong form of aggregation
always 0..1 or 1
Mouse
composite
1
composition
1..4
Button
part
The buttons have no independent existence. If we destroy the mouse, we destroy the buttons. They are an integral part of the mouse
The parts belong to exactly 0 or 1 whole at a time The composite has sole responsibility for the disposition of all its parts. This means responsibility for their creation and destruction The composite may also release parts provided responsibility for them is assumed by another object If the composite is destroyed, it must either destroy all its parts, OR give responsibility for them over to some other object Composition is transitive and asymmetric
Clear View Training 2005 v2.2 261
18.5.1
Attributes are in effect composition relationships between a class and the classes of its attributes Attributes should be reserved for primitive data types (int, String, Date etc.) and not references to other classes
262
18.7
18.8
trace
trace 1
design
roleName
1
roleName
One-to-one associations in analysis usually imply single ownership and usually refine to compositions
Many-to-one relationships in analysis imply shared ownership and are refined to aggregations
263
18.9
1 to many associations
To refine 1-to-many associations we introduce a collection class Collection classes instances store a collection of object references to objects of the target class A collection class always has methods for:
source
target 1 *
trace 1 1 1 *
Adding an object to the collection Removing an object from the collection Retrieving a reference to an object in the collection Traversing the collection
Vector
Collection classes are typically supplied in libraries that come as part of the implementation language In Java we find collection classes in the java.util library
Clear View Training 2005 v2.2 264
18.10
Collection semantics
property pair {unordered, nonunique} {unordered, unique} {ordered, unique} {ordered, nonunique}
OCL collection Bag Set (default) OrderedSet Sequence Clear View Training 2005 v2.2 265
{ordered, unique}
18.10.1
Maps
Maps (also known as dictionaries) have no equivalent in OCL Maps usually work by maintaining a set of nodes Each node points to two objects the "key" and the "value" Maps are optimised to find a value given a specific key They are a bit like a database table with only two columns, one of which is the primary key They are incredibly useful for storing any objects that must be accessed quickly using a key, for example customer details or products
m:HashMap
node1 key1 value1 key2 value2 key3 value3
node2
node3
{map}
18.11.1
There is no commonly used OO language that directly supports many-to-many associations We must reify such associations into design classes Again, we must decide which side of the association should have primacy and use composition, aggregation and navigability accordingly
Task
* Resource
trace
Task
Allocation
Resource
267
18.11.2
Bi-directional associations
There is no commonly used OO language that directly supports bidirectional associations We must resolve each bidirectional associations into two unidirectional associations Again, we must decide which side of the association should have primacy and use composition, aggregation and navigability accordingly
trace
1 A 1
this side has primacy
* B *
268
18.11.3
Association classes
There is no commonly used OO language that directly supports association classes Refine all association classes into a design class Decide which side of the association has primacy and use composition, aggregation and navigability accordingly
Company * Job
salary:double
Person
trace
Company
this side has primacy
Job
salary:double
Person
{each Person can only have one job with a given Company}
269
18.13
Summary
In this section we have seen how we take the incompletely specified associations in an analysis model and refine them to: Aggregation
Whole-part relationship Parts are independent of the whole Parts may be shared between wholes The whole is incomplete in some way without the parts A strong form of aggregation Parts are entirely dependent on the whole Parts may not be shared The whole is incomplete without the parts
Composition
One-to-many, many-to-many, bi-directional associations and association classes are refined in design
Clear View Training 2005 v2.2 270
271
19.3
Interfaces
An interface specifies a named set of public features It separates the specification of functionality from its implementation An interface defines a contract that all realizing classifiers must conform to:
Interface specifies operation attribute Realizing classifier Must have an operation with the same signature and semantics Must have public operations to set and get the value of the attribute. The realizing classifier is not required to actually have the attribute specified by the interface, but it must behave as though it has Must have an association to the target classifier. If an interface specifies an association to another interface, then the implementing classifiers of these interfaces must have an association between them Must support the constraint Has the stereotype Has the tagged value Realizes the protocol Clear View Training 2005 v2.2 272
design by contract
association
19.4
A provided interface indicates that a classifier implements the services defined in an interface
interface Borrow borrow() return() isOverdue()
interface
Borrow
realization relationship
Book
CD
Book
CD
Lollipop style notation (note: you cant show the interface operations or attributes with this shorthand style of notation)
273
19.4
A required interface indicates that a classifier uses the services defined by the interface
class style notation lollipop style notation
Library
Library
Library
interface Borrow
Borrow
Borrow
required interface
Clear View Training 2005 v2.2 274
19.4
Assembly connectors
You can connect provided and required interfaces using an assembly connector
1 Library 1
assembly connector
Borrow
0..*
Book
CD
0..* 275
19.6
A port specifies an interaction point between a classifier and its environment A port is typed by its provided and required interfaces:
It is a semantically cohesive set of provided and required interfaces It may have a name You can name the port portName:RequiredInterfaceName
If a port has a single required interface, this defines the type of the port
port
DisplayMedium
Viewer
Book
presentation presentation
Print, Display
Clear View Training 2005 v2.2
Book
276
19.7
Interfaces are the key to component based development (CBD) This is constructing software from replaceable, plug-in parts:
Plug the provided interface Socket the required interface Electrical outlets Computer ports USB, serial, parallel
Consider:
Interfaces define a contract so classifiers that realise the interface agree to abide by the contract and can be used interchangeably
277
19.8
What is a component?
The UML 2.0 specification states that, "A component represents a modular part of a system that encapsulates its contents and whose manifestation is replaceable within its environment"
A black-box whose external behaviour is completely defined by its provided and required interfaces May be substituted for by other components provided they all support the same protocol Physical - can be directly instantiated at run-time e.g. an Enterprise JavaBean (EJB) Logical - a purely logical construct e.g. a subsystem
278
19.8
Component syntax
Components may have provided and required interfaces, ports, internal structure
Provided and required interfaces usually delegate to internal parts You can show the parts nested inside the component icon or externally, connected to it by dependency relationships
black box notation component white box notation
component
part
required interface
A B
I1 delegate
provided interface
C
I2 delegate
component
I1
19.9
Semantics
A component that defines a set of things for organizational or system level development purposes. A persistent information component representing a business concept. A component definition that is not intended to have a specification itself. Rather, it is an implementation for a separate specification to which it has a dependency. A classifier that specifies a domain of objects without defining the physical implementation of those objects. For example, a Component stereotyped by specification only has provided and required interfaces - no realizing classifiers. A transaction based component.
specification
process
service
subsystem
19.10
Subsystems
A subsystem is a component that acts as a unit of decomposition for a larger system It is a logical construct used to decompose a larger system into manageable chunks Subsystems can't be instantiated at run-time, but their contents can Interfaces connect subsystems together to create a system architecture
Clear View Training 2005 v2.2
subsystem
GUI
Order Manager
subsystem
Business Logic
281
19.11
Look for repeating groups of operations Look for groups of operations that might be useful elsewhere Look for possibilities for future expansion Look for cohesive sets of provided and required interfaces and organize these into named ports Look at the dependencies between subsystems - mediate these by an assembly connector where possible
Clear View Training 2005 v2.2 282
19.12
Design interfaces based on common sets of operations Design interfaces based on common roles
These roles may be between two classes or even within one class which interacts with itself These roles may also be between two subsystems
Design interfaces for new plug-in features Design interfaces for plug-in algorithms The Faade Pattern - use interfaces can be used to create "seams" in a system:
Identify cohesive parts of the system Package these into a subsystem Define an interface to that subsystem
19.12.2
Physical architecture
Subsystems and interfaces comprise the physical architecture of our model We must now organise this collection of interfaces and subsystems to create a coherent architectural picture: We can apply the "layering" architectural pattern
Subsystems are arranged into layers Each layer contains design subsystems which are semantically cohesive e.g. Presentation layer, Business logic layer, Utility layer Dependencies between layers are very carefully managed Dependencies go one way Dependencies are mediated by interfaces
Clear View Training 2005 v2.2 284
19.12.2
subsystem Customer
subsystem Order
Account Manager
subsystem Product
subsystem Accounts
utility
subsystem javax.swing
19.13
Using interfaces
Advantages:
When we design with classes, we are designing to specific implementations When we design with interfaces, we are instead designing to contracts which may be realised by many different implementations (classes) Designing to contracts frees our model from implementation dependencies and thereby increases its flexibility and extensibility
Interfaces can add flexibility to systems BUT flexibility may lead to complexity Too many interfaces can make a system too flexible! Too many interfaces can make a system hard to understand
Disadvantages:
Keep it simple!
Clear View Training 2005 v2.2 286
19.14
Summary
They define a contract that classes and subsystems may realise Programming to interfaces rather than to classes reduces dependencies between the classes and subsystems in our model Programming to interfaces increases flexibility and extensibility
Componentize our system Define an architecture
Clear View Training 2005 v2.2 287
288
20.3
A collaboration of Design objects and classes that realise a use case A Design use case realization contains
Design object interaction diagrams Links to class diagrams containing the participating Design classes An explanatory text (flow)
There is a trace between an Analysis use case realization and a Design use case realization The Design use case realization specifies implementation decisions and implements the non-functional requirements
Clear View Training 2005 v2.2 289
20.4
We only produce a design interaction diagram where it adds value to the project:
A refinement of the analysis interaction diagrams to illustrate design issues New diagrams to illustrate technical issues New diagrams to illustrate central mechanisms
In design:
Sequence diagrams are used more than communication diagrams Timing diagrams may be used to capture timing constraints
290
20.4
:Registrar
:RegistrationUI
:RegistrationManager
:DBManager
291
20.5
ControlBox
1
You can show concurrency on sequence diagrams by giving each thread of execution a name and appending this name to the messages (see next slide)
SecuritySensorMonitor
1 0..*
FireSensorMonitor
1 0..*
SecuritySensor
FireSensor
292
20.5.2
activate()
par
soundActivatedAlarm()
monitor()
loop 1, * [!fire] critical fire = isTriggered()
intruder = isTriggered()
opt [!fire]
intruder()
soundIntruderAlarm()
293
20.5.3
1.3 B : soundIntruderAlarm ()
:ControlBox 1.2 A : fire() 1.2 B : intruder() 1.1 B : monitor() :Siren
:SecurityGuard
1.1 A : monitor()
Messages labelled A execute concurrently to messages labelled B e.g. 1.1 A executes concurrently to 1.1 B
Clear View Training 2005 v2.2 294
20.6
Subsystem interactions
Sometimes its useful to model a use case realization as a high-level interaction between subsystems rather than between classes and interfaces
Model the interactions of classes within each subsystem in separate interaction diagrams
subsystem
Customer
20.7
Timing diagrams
Emphasize the realtime aspects of an interaction Used to model timing constraints Lifelines, their states or conditions are drawn vertically, time horizontally It's important to state the time units you use in the timing diagram
sd IntruderThenFire
duration constraint soundingFireAlarm {t <= 15} {t = 30} fire event intruder intruder 0 10 20 30 40 50 60 70 time in minutes 80 90 100
:Siren
lifeline soundingIntruderAlarm
state or condition
off
resting
timing ruler
sd IntruderThenFire
state or condition
:Siren
compact form
off
resting
296
20.7
You can show messages between lifelines on timing diagrams Each lifeline has its own partition
{t <= 0.016}
notTriggered
{t <= 0.016} triggered messages
:IntruderSensorMonitor
notTriggered soundFireAlarm() soundingFireAlarm soundIntruderAlarm() soundIntruderAlarm() soundIntruderAlarm() soundIntruderAlarm() off resting {t <= 15} {t = 30} {t <= 15}
soundingIntruderAlarm :Siren
297
Example
20.8
298
20.9
Summary
299
300
21.2
State machines
Some model elements such as classes, use cases and subsystems, can have interesting dynamic behavior - state machines can be used to model this behaviour Every state machine exists in the context of a particular model element that:
Responds to events dispatched from outside of the element Has a clear life history modelled as a progression of states, transitions and events. Well see what these mean in a minute! Its current behaviour depends on its past
A state machine diagram always contains exactly one state machine for one model element There are two types of state machines (see next slide):
Behavioural state machines - define the behavior of a model element e.g. the behavior of class instances Protocol state machines - Model the protocol of a classifier
The conditions under which operations of the classifier can be called The ordering and results of operation calls Can model the protocol of classifiers that have no behavior (e.g. interfaces and ports) Clear View Training 2005 v2.2 301
21.4
On
burnOut
Off
On
21.4
On
burnOut
Event = turnOn
Off
On
We throw the switch to On and the event turnOn is sent to the lightbulb
303
21.4
Light bulb On
State = on light bulb {protocol} turnOn Off turnOff
On
burnOut
Off
On
304
21.4
On
burnOut
Event = turnOff
Off
On
We turn the switch to Off. The event turnOff is sent to the light bulb
305
21.4
On
burnOut
Off
On
306
21.4
A
start state
anEvent
transition state
B
final state
Every state machine should have a start state which indicates the first state of the sequence Unless the states cycle endlessly, state machines should have a final state which terminates the sequence of transitions Well look at each element of the state machine in detail in the next few slides!
Clear View Training 2005 v2.2 307
21.5
States
"A condition or situation during the life of an object during which it satisfies some condition, performs some activity or waits for some event" The state of an object at any point in time is determined by:
The values of its attributes The relationships it has to other objects The activities it is performing
Clear View Training 2005 v2.2 308
21.5.1
State syntax
Entry actions occur immediately on entry to the state Exit actions occur immediately on leaving the state
state name entry and exit actions internal transitions internal activity
EnteringPassword
entry/display password dialog exit/validate password
Internal transitions occur within the state. They do not transition to a new state Activities take a finite amount of time and are interruptible
21.6
Transitions
behavioral state machine
event1, event2 [guard condition] / act1, act2 events Boolean guard condition actions
310
21.6.1
A
t1
t2
B
merge with branch
D A
t1 [c1] t2 [c2]
21.6.2
The choice pseudo state directs its single incoming transition to one of its outgoing transitions Each outgoing transition must have a mutually exclusive guard condition
Loan
Unpaid
choice pseudo-state acceptPayment
[payment = balance]
FullyPaid
makeRefund
OverPaid
PartiallyPaid
312
21.7
Events
"The specification of a noteworthy occurrence that has location in time and space" Events trigger transitions in state machines Off Events can be shown externally, on transitions, or internally within states turnOff turnOn (internal transitions) There are four types of event: event
On
313
21.7.1
Call event
A call for an operation executon The event should have the same signature as an operation of the context class A sequence of actions may be specified for a call event - they may use attributes and operations of the context class The return value must match the return type of the operation
SimpleBankAccount
action
close()
condition
withdraw(m) [balance >= m]
RejectingWithdrawal
entry/ logRejectedWithdrawal()
AcceptingWithdrawal
entry/ balance = balance - m
entry action
314
21.7.2
Signal events
SimpleBankAccount
close()
InCredit
deposit(m)/ balance = balance + m withdraw(m) [balance < m] withdraw(m) [balance >= m]
RejectingWithdrawal
entry/ logRejectedWithdrawal()
AcceptingWithdrawal
entry/ balance = balance - m
OverdrawnAccount
date : Date accountNumber : long amountOverdrawn : double OverdrawnAccount
send a signal
315
21.7.2
Receiving a signal
You may show a signal receipt on a transition using a concave pentagon or as an internal transition state using standard notation
OverdrawnAccount
Calling borrower
signal receipt
316
21.7.3
Change events
InCredit
[balance>=0] [balance<0]
A change event is a Boolean expression The action is performed when the Boolean expression transitions from false to true
Overdrawn
balance < overdraftLimit / notifyManager Boolean expression action
The event is edge triggered on a false to true transition The values in the Boolean expression must be constants, globals or attributes of the context class
From the implementation perspective, a change event implies continually testing the condition whilst in the state
317
21.7.3
Change events
The action is performed when the Boolean expression transitions from false to true
SimpleBankAccount
close()
The event is edge triggered on a false to true transition The values in the Boolean expression must be constants, globals or attributes of the context class
RejectingWithdrawal
entry/ logRejectedWithdrawal()
AcceptingWithdrawal
entry/ balance = balance - m
A change event implies continually testing the condition whilst in the state
OverdrawnAccount
318
21.7.4
Time events
Time events occur when a time expression becomes true There are two keywords, after and when Elapsed time:
Overdrawn
balance < overdraftLimit / notifyManager
after( 3 months )
Frozen
Absolute time:
319
21.8
Summary
Actions
Transitions
Events
321
22.2
Composite states
A composite state
region 1
A C
B
submachines
The final state terminates its enclosing region all other regions continue to execute The terminate pseudo-sate terminates the whole state machine Use the composition icon when the submachines are hidden
A composite state
composition icon
322
22.2.1
ISPDialer DialingISP
entry/ offHook
dial WaitingForDialtone [dialtone] after(20 seconds)/ noDialtone Dialing do/ dialISP entry pseudo state after(20 seconds)/ noCarrier [carrier] WaitingForCarrier
cancel
exit pseudo-state
connected Connected
22.2.2
Has two or more regions When we enter the superstate, both submachines start executing concurrently - this is an implicit fork
Unsynchronized exit - exit the superstate when either region terminates. The other region continues
Monitoring composite state details Monitoring MonitoringFireSensors do/ monitorFireSensor MonitoringSecuritySensors do/ monitorSecuritySensor fire
Synchronized exit - exit the superstate when both regions have terminated
Initializing composite state details Initializing InitializingFireSensors do/ initializeFireSensor InitializingSecuritySensors do/ initializeSecuritySensor
intruder
324
22.3
Submachine states
If we want to refer to this state machine in other state machines, without cluttering the diagrams, then we must use a
VerifyingUser
LoggingIn
GettingDetails
do:getUsername do:getPassword
cancel cancelled
submachine state
getDetails
Submachine states reference another state machine Submachine states are semantically equivalent to composite states
verified [badUsername]
verifyDetails
Verifying
do:getUsername do:getPassword
badUsername
[badPassword]
badPassword
325
22.3
A submachine state is equivalent to including a copy of the submachine in place of the submachine state
CheckingOut
submachine state
CancellingCheckout
cancelled
AcceptingPayment [!ok]
[ok]
succeeded
paymentFailed
[noDetails]
[details]
checkOut
AssessCustomer
326
22.4
Submachine communication
We often need two submachines to communicate Synchronous communication can be achieved by a join Asynchronous communication is achieved by one submachine setting a flag for another one to process in its own time.
Submachine communication using the attribute PaidFor as a flag: The upper submachine sets the flag and the lower submachine uses it in a guard condition
[paidFor]
DeliveringOrder
do/assemble order
Clear View Training 2005 v2.2 327
22.5.1
Shallow history Browsing remembers the last substate at the same level as return exit the shallow history pseudo state Next time the super state is entered there is an automatic transition to the remembered browseIndex substate
goToIndex
selectProduct
DisplayingIndex
CheckingOut
Alphabetical
byCategory alphabetical goToCatalog
ByCategory
this fires the first time the history state is entered shallow history pseudo-state
328
22.5.2
Deep history remembers the last substate at the same level or lower than the deep history pseudo state
Browsing
BrowseCatalog return exit goToBasket DisplayingItem goToCheckout goToCheckout DisplayingBasket goToCatalog
goToIndex
selectProduct
DisplayingIndex
CheckingOut
Alphabetical
byCategory alphabetical goToCatalog
329
22.6
Summary
Attribute values
Implementation - introduction
331
23.2
Implementation - purpose
Inception
Elaboration
Construction
Transition
23.3
Design Model
Component diagrams showing components and the artifacts that realize them Deployment diagrams showing artifacts deployed on nodes
node
component c2
manifest
333
23.4
Implement a class
Component engineer Implement a component Clear View Training 2005 v2.2 Perform unit test 334
23.6
Summary
Implementation begins in the last part of the elaboration phase and is the primary focus throughout later stages of the construction phase Purpose to create an executable system artifacts:
component diagrams
deployment diagrams
335
Implementation - deployment
336
24.3
Deployment model
The deployment model is an object model that describes how functionality is distributed across physical nodes
It models the mapping between the software architecture and the physical system architecture Each node is a type of computational resource Nodes have relationships that represent methods of communication between them e.g. http, iiop, netbios Artifacts represent physical software e.g. a JAR file or .exe file Focus on the big picture - nodes or node instances and their connections Leave detailed artifact deployment to the implementation workflow Focus on artifact deployment on nodes
337
24.4
0..*
http
0..*
association
node
e.g. a WindowsPC
24.4
device JimsPC:WindowsPC
device WebServer1:LinuxPC
http
device IlasPC:WindowsPC
node instance
339
24.4
Stereotyping nodes
IBM RS/6000
Printer
Its very useful to use lots of stereotyping on the deployment diagram to make it as clear and readable as possible
Clear View Training 2005 v2.2 340
24.5
Artifacts
The artifact is the represents the thing that is the physical manifestation of the component (e.g. a JAR file)
341
24.5
Artifacts provide the physical manifestation for one or more components Artifacts may have the artifact icon in their upper right hand corner Artifacts can contain other artifacts Artifacts can depend on other artifacts
artifact jdom.jar
LibraryImpl
1 1
BookImpl
TicketImpl
Book
Library
Ticket
342
24.5
Artifact relationships
An artifact may depend on other artifacts when a component in the client artifact depends on a component in the supplier artifact in some way
artifact librarySystem.jar artifact ISBN.class artifact BookImpl.class artifact LibraryImpl.class artifact TicketImpl.class artifact TicketID.class
artifact jdom.jar
artifact Book.class
artifact Library.class
artifact Ticket.class
343
24.5
artifact stereotype file deployment spec document executable library script source
24.5
Stereotyping artifacts
e.g. applying the example Java profile from the UML 2 specification
JAR librarySystem.jar JavaClassFile ISBN.class JavaClassFile BookImpl.class JavaClassFile LibraryImpl.class JavaClassFile TicketImpl.class JavaClassFile TicketID.class
JAR jdom.jar
JavaClassFile Book.class
JavaClassFile Library.class
JavaClassFile Ticket.class
345
24.6
Deployment
Artifacts are deployed on nodes, artifact instances are deployed on node instances
device server:WindowsPC
device client:WindowsPC
RMI
JAR :ConverterClient.jar
JAR :ConverterApp.ear
346
24.7
Summary
Allows you to show how functionality represented by artefacts is distributed across nodes Nodes represent types of physical hardware or execution environments
Allows you to show how functionality represented by artefact instances is distributed across node instances Node instances represent actual physical hardware or execution environments
Clear View Training 2005 v2.2 347
Course summary
348
Inception Elaboration
Construction
Transition
We have now covered the 4 UP workflows in which OO analysts and designers participate
Next steps
"UML 2and the Unified Process" "Enterprise Patterns and MDA" Literate modeling Archetype patterns
SUMR - open source use case modeling tools Speak directly to the course author Dr. Jim Arlow:
Jim.Arlow@clearviewtraining.com
Further training, mentoring and consultancy in all aspects of object technology and project management is available from:
Zuhlke Engineering Limited (UK), Zhlke Engineering AG (Switzerland) and Zhlke Engineering GmbH (Germany) - www.zuhlke.com
Clear View Training 2005 v2.2 350
Finally
We hope you enjoyed this course and that well see you again soon! Wed find it really useful if youd fill in your course evaluation forms before leaving.
Bye!
351