SLIDE 1
Unified Modeling Language (UML)
SLIDE 2
Unified Modeling Language (UML)
Learn how to understand and draw UML diagrams
SLIDE 3
Agenda Introduction Use Case Diagrams Class Diagrams Activity Diagrams State Diagrams Interaction Diagrams
Sequence Diagrams Communication Diagrams
Package Diagrams Deployment Diagrams Position and History of UML
SLIDE 4
Reference
‘UML Distilled, 3rd Edition’ by Martin Fowler
SLIDE 5
Unified Modeling Language (UML)
Introduction
SLIDE 6
Introduction (1) Unified Modeling Language is ...
… a general purpose visual modeling language for systems … explicitly designed to be implemented by CASE tools
(computer-assisted software engineering) … not a modeling methodology
But can be used to construct models
Unified across several different domains Development:
requirements → implementation Application:
business process → real-time systems Implementation language:
OO → non-OO languages
SLIDE 7
Introduction (2) UML states that a system (software or other) contains
collections of collaborating objects An object is a cohesive cluster of data and behaviour
Contains information and performs functions Aspects of a UML model:
Static structure Type of objects Relation between objects
Dynamic behaviour Life cycle of objects (internal state) Collaboration between objects
SLIDE 8
The structure of UML consists of Building blocks Common mechanisms Architecture
Introduction (3)
SLIDE 9
Modeling elements Relations: how elements are semantically related
Association, dependency, generalization, realization Diagrams: show collections of elements
What the system does – analysis level diagrams How it will be done – design level diagrams
Building Blocks
SLIDE 10
Common ways of achieving specific goals Are applied in different contexts throughout UML
Specifications Textual description (besides the visual) of the elements Hold the model together, give it meaning
Adornments To increase clarity, when more information is needed
Common divisions Describe particular ways of thinking about the world
– Classifier and instance (abstract – concrete)– Interface and implementation (what – how)
Extensibility mechanisms { constraint } : simple text in braces { } <<stereotype>> : variation on an existing element with different intent { keyword = value }-list : tagged value, property of an element, often
used to store version information
Common Mechanisms
SLIDE 11
The organizational structure of a system Its decomposition into parts, their connectivity,
interactions ... the design of the system Different views:
Logical view Vocabulary of the system as a set of classes and behaviour
Process view Process-oriented variation of the logical view, a set of active classes
Implementation view Files and components that make up the physical code base of the
system Deployment view
Distribution of components across the nodes of a distributed system Use case view
Basic requirements of a system, integrates the 4 previous views
Architecture
SLIDE 12
UML Diagrams
SLIDE 13
Unified Modeling Language (UML)
Use Case Diagrams
SLIDE 14
High-level specification Use to discover / reach agreement on what the system should do
Expressed in the language of the end-users Negotiation on conflicting requirements Captures only functional requirements:
What the system will do Nothing about non-functional requirements as performance,
reliability … but usually discovered while working on it Workflow and tasks:
Find functional requirements Discover non-functional requirements Prioritize requirements Trace them into use cases
Purpose of Use Cases (1)
SLIDE 15
Failure of a software project due to Failure in requirements engineering Lack of end-user involvement …
Apply filters when gathering information Deletion: filter information out Distortion: modify information Generalization: create rules, principles about truth and falsehood
Look for universal qualifiers such as all, everyone, always, nobody…. Indicate a limit, bound of someone’s idea Challenge your users by asking: “Is it really so ...?”
Purpose of Use Cases (2)
SLIDE 16
Use Case Definition Use case captures the functional requirements
Find system boundary Find actors Find the use cases
Described within several scenario’s A scenario is a sequence of steps
Scenarios tied together by a common user goal: Example: ‘buy a product’-case
‘Normal’ ‘No shipping and credit card information’ ‘Credit card authorization fails’
SLIDE 17
Rectangle indicates the system boundary Actor
Use case
Descriptions
Symbols (1)
SLIDE 18
Symbols (2) Relations between scenarios are called dependencies:
a dashed line with navigation arrow
Relations between actors are called associations: line with use case scenario in between
SLIDE 19
Symbol Definitions Primary actor (initiator)
Calls the system to deliver a service The actor with the goal the use case tries to satisfy
A step is a simple statement Shows who is carrying out the step
Use cases do not describe the user interface Use cases can include other use cases
To avoid too complex or repeating steps Use cases can have extensions
Actions that do not always happen
SLIDE 20
First step: determine the system boundary Define what is part of the system and what is external to
the system Has impact on functional requirements Is defined by who/what uses the system Is drawn as a rectangle labelled with a name
System Boundary
SLIDE 21
Actors (1) Second step: finding the actors Use following questions:
Who/what uses the system? What role do they play in their interactions with the system? Who installs, maintains, start/stops the system? What other systems interact with this system? Who gets/provides information from/to the system? Does anything happen at a fixed time? . . .
SLIDE 22
Actors (2) An actor is a role that an external entity plays with
respect to the system, not to specific people or things Is a stereotype of a certain class Can be non-human, or a service of another system Always external to the system
Is given a name that makes sense from the business perspective
Remark: A single actor → many use cases A single use case → several actors A single user → more than one actor
SLIDE 23
A Use Case … ... is a specification of sequences of actions the system
can perform by interacting with outside actors ... is given a name that is a verb sentence ... is built during an iterative process, with stepwise
refinement ... can be found by starting with a list of actors, then:
What function does the actor want from the system? Does the system store, retrieve information ? Are actors notified when the system changes ? Are there any external events that effect the system? What notifies the system ?
SLIDE 24
The <<include>> relationship between use cases allows to include behaviour of one use case (the supplier) into the flow of another use case (the client)
To avoid repeating steps
Include
SLIDE 25
Use Case Diagram Example
SLIDE 26
Extension Within the <<extend>> relationship, the base use case
knows nothing about the extending use case Each extension
Adds new behaviour to an existing use case Names a condition that results in different interactions
SLIDE 27
The UML symbols describe only the use cases, and how they interrelate They do not describe how to capture the content for use cases
You will need to describe the content in a textual format, as a flow of events: Describe all the scenario’s Pick one as the main scenario The others become extensions, written in function of the main
scenario
Use Case Content
SLIDE 28
Defining the Steps (1) Each use case step has the form
<number> the <something> <some action> Well-formed, good practice
‘1. the customer enters his name, address into the form’ Omissions, bad practice
‘1. customer details are entered’ Missing: who enters the details, into what are the details entered,
what are the details, …
SLIDE 29
Branching within the flow Instead of creating a new use case for each individual action,
branch within the flow Use the keywords if – for each – while
Defining the Steps (2)
SLIDE 30
Other information can be added to the content Pre-condition
Conditions before the use case will begin Prevent an actor from triggering the use case until all the pre-
conditions are met Guarantees / post-conditions
What the system will ensure at the end Triggers
The events that get the use case started
Content Additions
SLIDE 31
Defining Extends 2 different approaches First approach:
Differences are described in steps The last step states where the extension returns to
Second approach: base and extension use case 1. … 2. … <regular customer> 3. …
SLIDE 32
Extends Example
SLIDE 33
Unified Modeling Language (UML)
Class DiagramsAnalysis
SLIDE 34
A class diagram describes classes It classifies objects into “types”
Classifier / instance Realization of an abstraction
Inheritance: multiple levels of classification Classify into subclasses
Composition: strong relationship between some objects An object belongs to one class Its life cycle is intimately tied to the class
Aggregation: loose relationship An object can belong to multiple classes It will survive its owner
Classification
SLIDE 35
Class Diagram Definitions A well-defined class
Has a name that reflects its intent Is the abstraction of one specific element Has a small (3-5) set of responsibilities High cohesion Low coupling
A class diagram is An abstraction of the problem domain A mapping on to real-world business concepts Made of several related classes The vocabulary of the system
SLIDE 36
Finding Classes Noun-verb analysis
Nouns → classes and/or attributes Verbs → responsibilities, operations of a class Resolve all synonyms and homonyms
CRC analysis (Class – Responsibility – Collaborator) Gather information
All ideas No discussion Name all ‘things’
Analyse the found information Key business → a class Part of another thing → an attribute, or a class Unimportant → look for a class to fit it into
SLIDE 37
Warning! Avoid at all costs the large “Swiss Army Knife”
Type of class that tries to do all things for everyone Also known as “the Blob” or “the God class”
Example: a Guest staying at an Hotel Notice too much responsibilities Notice too low cohesion
SLIDE 38
Analysis Classes Analysis classes are classes that
Represent a crisp abstraction of the domain Model what the system must do
Much of the preparation is done while gathering the requirements and creating a use case model
They represent a very high level Set of attributes Set of key services
They indicate the attributes and the behaviour that the resulting design class will probably have
Design classes will have a lot more details
SLIDE 39
Class Definition A class defines a common set of features, shared by all
instances Properties and operations
A class diagram describes The types of objects The relationships among those objects Which classes are linked to one another
At least one object must have a reference to another A relationship is a dynamic connection, not fixed over time
The constraints that apply to the way objects are connected (multiplicity)
SLIDE 40
Properties A property is a structural feature A property can be
An attribute An association with another object
Attributes → for small things Booleans, dates, value types, primitives
Associations → significant classes Customer, Order Can have a multiplicity description on both sides
SLIDE 41
Attributes An attribute is described as a line of text within the class
box itself
Syntax visibility name : type multiplicity = default {property-String}
Examplename:String[1] = "Untitled" {readOnly}
SLIDE 42
Association An association between 2 classes
Is a solid line, called a link Navigation arrow indicates direction in which messages are sent
The owning side contains the reference to the other object (target) No arrow indicates bi-directional
Verb phrase as it’s name, pre or post-fixed with small arrowhead Shows the reading direction
The (target) end Has the role name of the association The multiplicity Is the type of the property from the owner side
SLIDE 43
Property Example Attribute
Association
SLIDE 44
Multiplicity Multiplicity of an property indicates how many objects
may fill that property at any point in time Implies a constraint
A Person must always be employed A Person can only be employed by one Company at a given time
Are defined with a lower and upper bound 1 (no null allowed) , * , 0..1 (null values allowed)
Additional information {ordered} , {nonunique}, {bag}
SLIDE 45
Reflexive Associations Example of reflexive associations Composite pattern as popular example
SLIDE 46
Operations Operations
The actions / behaviour / services of a class Correspond to the methods of the class Messages for communication between objects
Accessors are often omitted in the diagram To retrieve or change a property Prefixes with get or set + property-name (Java)
Syntax visibility name (parameters) : return-type {property-string} Parameters have a notation similar to attributes Parameters can be extended with a direction in, out, inout
SLIDE 47
Constructors Constructors are special operations
Universal → create() Java, C# → same name as class Do not have a return value (they return an instance)
Enable clients to construct an instance of the class Primary task is to initialize the class properties
SLIDE 48
Destructors Special operation for cleaning up when objects are
destroyed Language dependent
C++: ~constructorname(paramList) Guaranteed to be called
C#, java: Objects are not explicitly deleted by the program Deleting is left to garbage collector (GC) Some methods provide possible functionality: Finalize(); finalize(); No guarantees when this method will be called by GC
SLIDE 49
Responsibilities Rule
Each OO concept (class – method – ... ) has one and only one responsibility
Use the Command-Query principle aka “the principle of least surprise”: Operations that change the state of an object (set*)
Modifiers Do not return values
Operations that query the object (get*) Considered to be just queries Return a value, but do not modify the state
SLIDE 50
Visibility All class members (properties, operations) can have a
different visibility Visibility determines who has access to the member UML symbols:
private - // only the owning class package ~ // all classes within the same package protected # // as package and all subclasses public + // any class
Be careful: each language has its own interpretation!
SLIDE 51
Encapsulation Encapsulation = data hiding Leads to more robust software This has to be done for security reasons
The developer of the class knows perfectly what the functionality and responsibility of the class is
If the class has new requirements, then the only place to implement those requirements is in the class itself
This has to be done to make that all properties of a class stay consistent with their primary purpose What would happen if the property salary in an object Person was
public?
SLIDE 52
Encapsulation Remarks OO design is about objects with a rich set of
Behaviour Responsibilities
OO classes must be more than a collection of Attributes Their accessors
Too many calls to the accessors is a sign that the behaviour should be known by the class itself
SLIDE 53
Encapsulation Example How to calculate the price of an instance of OrderLine ?
Consider this requirement as the responsibility of the instance and not of the client who uses this instance
Solution: add a calculatePrice()-method to the OrderLine
SLIDE 54
Property Remarks (1) An UML property leads to a programming interpretation
Can be different for each individual language A field or a property in the code
Do not use a field for every UML property! Some fields can be calculated
SLIDE 55
Property Remarks (2) A property represents something an object owns A property is unique and typically for that object
Do not use a property to model a transient relationship Objects passed as argument for one-time usage
Example:
SLIDE 56
Generalization Generalization for objects with
Many similarities → placed in a super-class Some differences → placed in a subclass
Conceptual view The subclass is a special kind of super-class object All that can be said of the super-class is valid for the subclass
Software view The subclass inherits everything of the super-class Can override some behaviour of the super-class
SLIDE 57
Substitutability Substitutability is an important principle of inheritance
Dynamic binding If code is written for a super-class, no code change is needed in
the clients if a subclass object is used instead of the super-class
SLIDE 58
Providing Substitutability Providing substitutability by
Using inheritance often includes too much or even undesirable behaviour clients have too much liberty in implementing the behaviour by
subclassing Implementing an Interface
If possible prefer composition over inheritance, as inheritance requires a strong compile time dependency
SLIDE 59
Dependencies (1) A dependency models a relationship between classes
that is not really an association Changes made to the first (supplier), will reflect on the
second (client) Reasons for dependencies
A class sends messages to another class A class is a part of another class A class is an argument for a method of
another class
SLIDE 60
Dependencies (2) Many relationships “imply” a dependency Some keywords are available in UML to indicate the type
of dependency <<use>>: the client uses a service to implements its own
behaviour <<abstraction>>: supplier more abstract, at different point in
development (ex: in analysis model rather then design model) <<permission>>: supplier grants permission to access its content
SLIDE 61
Dependencies (3) Other keywords are allowed if they suits the purpose
<<parameter>> <<local>> the object is declared in a method <<global>> the object is an attribute ...
Use a stereotype for your own keywords
SLIDE 62
Transitive Behaviour Transitivity
A > B, B > C => A > C Substitutable and direct dependencies are transitive:
The dependencies stay until the lowest class Indirect dependencies are usually not transitive:
See the Window-Employee example Changes in EmployeeData, will invoke changes in Employee but not
in BenefitsWindow. If and only if those changes concern the implementation and not the
interface / use of Employee
SLIDE 63
Indirect Dependency Example
SLIDE 64
Dependency Warnings! Avoid dependencies!
They are hard to maintain Not flexible when changing requirements
Keep dependencies only in one direction Changes and their consequences easier to manage
Use dependencies only between closely related classes
SLIDE 65
Constraints A class diagram contains many constraints Associations, attributes, generalization … are all about
constraints: How many? Who depends on who? Who is related to who?
Some constraints can not be visualized For others constraints: place a description of the
constraint between { } In natural language Programming language Using OCL (Object Constraint Language)
http://www.omg.org/technology/documents/formal/ocl.htm
SLIDE 66
Example Class Diagram
SLIDE 67
When to Use Class Diagrams Class diagrams are the backbone of UML Are very rich in elements Can be too rich
Use the notations only when it is useful for the current particular case
Use class diagrams to explore the business language Keep out any software implementation issues
Provide a common vocabulary about the business Always keep structure, behaviour and patterns in mind
while designing the classes and their relations
SLIDE 68
Unified Modeling Language (UML)
Class DiagramsDesign
SLIDE 69
From Analysis to Design Moving from analysis to design, relationships between
analysis classes must be refined into the design classes Many relationships can not directly be implemented as
they are The design classes must specify how things will be implemented They contain a lot of details
A single analysis concept may result into several concepts within the resulting design classes
Example Analysis operation checkIn() is a high level specification of a piece
of functionality The resulting design method is a fully specified function: checkIn()
will consists of weighLuggage(), controlePass()
SLIDE 70
Viewpoints (1) Look at the class from the viewpoint of its clients / users
Completeness and sufficiency Primitiveness High cohesion Low coupling
SLIDE 71
Viewpoints (2) Completeness and sufficiency
public methods Contract between class and his client Give what the client expects or implies just by knowing the name of
the class Sufficient means nothing more than what the client expects
Primitiveness Do not offer multiple ways of doing the same thing
Confusing and hard to maintain Except if performance is an issue
Multiple calls to a simple method can be too expensive Provide alternative implementations depending on the context
SLIDE 72
Viewpoints (3) High cohesion
One single abstract concept per class Only add methods to support that concept Other responsibilities are delegated to helper-classes
Low coupling Strict separation in layers: presentation, business, data Associate a class with just enough other classes
Do not couple just to reuse some code High coupling can be compared to “spaghetti code”
Incomprehensible and hard to maintain
SLIDE 73
Inheritance Issues Inheritance is great for polymorphism and code reuse,
but can have undesirable characteristics Very strong coupling Weak encapsulation, changes in the base class reflects in the
derived classes Inflexible, fixed relationship at compile time
What if a Person wants to be an Author and an Illustrator?
What if an Author wants to be an Illustrator?
SLIDE 74
Multiple Inheritance Multiple inheritance is not supported by Java nor C#
SLIDE 75
Associations versus Inheritance Using an association can remove the undesirable
inflexible characteristics of inheritance
SLIDE 76
Aggregation versus Composition In design phase an association can be refined into an
aggregation or a composition The difference concerns the strength of the relationship
among the classes
SLIDE 77
Aggregation Aggregation
Solid line Open diamond on the source class
Indicates a whole-part and loose relationship A computer and its peripherals A class and its students
The source class (aggregate) can sometimes exist independently of the parts, sometimes not It is incomplete if a part is missing
The target class can exist independently of the aggregate Can even be shared by several aggregates
SLIDE 78
Aggregation Example
SLIDE 79
Composition Composition
Solid line Closed diamond on the source class
Indicates a whole-part and strong relationship A tree and its leaves A bread and its slices
An instance of the target class Is a part of the source (composite) class Has no reasons to exist if the source instance is null
Its life cycle is controlled by the source class Usually leads to a cascading delete
Many potential owners can be shown But it must be a component of only one owner Cannot be shared with other classes or instances!
SLIDE 80
Composition Examples
SLIDE 81
Abstract Classes and Interfaces An abstract class is a special class
Zero or more methods are abstract Abstract methods don’t have an implementation Implementation is provided by the extending class class symbol + keyword { abstract } or {A}
An interface is a special class Constants and methods without implementation Implementation is provided by the implementing class class symbol + stereotype <<interface>> No convention about << >> or { }
The name is often italicized Which is very difficult to draw
SLIDE 82
Abstract Class and Interface Examples
SLIDE 83
Interface An interface is a named set of operations, with NO
relationship to anything else Separates of the specification (what) from the
implementation (how) of a functionality Design by interfaces is a very flexible solution Interfaces provide the “plugs and sockets” for the model
SLIDE 84
Interface Example Interfaces allow to connect things without coupling them An applications uses the interface INr to handle the
different sort of numbers in the same way, just as if they were the same
Different types of INr objects can be plugged in
SLIDE 85
Interface Relationships Two kind of relationships between classes and interfaces A class provides an interface if the class
Is substitutable for the interface Has an implementation of all the methods
A class requires an interface if the class Needs an interface in order to work Has a dependency with the interface
SLIDE 86
Java Library Interface Example
SLIDE 87
The Lollipop Notation Another, more compact notation for interfaces Socket icon
Needs an interface That interface variable will be substituted for an instance
Lollipop icon Provides an interface Implements the interface
SLIDE 88
The Lollipop Notation Example
SLIDE 89
Finding Interfaces Finding interfaces
Challenge each association Should it really be to a particular class of objects?
Challenge each message send Is it really sent to objects of just one class?
Factor out group of operations that might be reusable Factor out sets of operations that are repeated Look for classes that play the same role in the system Look for possibilities for future expansion
Interfaces define a protocol, new classes can easily be added to the system if they respect that protocol
SLIDE 90
Disadvantage of Interfaces The cost of more flexibility is the fact that the system
becomes more complex Interfaces can also influence the performance of the
system You might be doing too much when trying to be prepared
for every change (reason for designing to interfaces), as Some requirements do change often But others are left out or will never change
A system must be correctly modelled Can become difficult or in dangerous if it is flexibly modelled
KISS rule: Keep It Stupidly Simple
SLIDE 91
Unified Modeling Language (UML)
Class DiagramsAdvanced Concepts
SLIDE 92
Inheritance and Subclassing Classes arranged into a generalization hierarchy take
advantage of inheritance All non-private features of the super class are inherited Subclasses can
Add new features Change the behaviour defined in the super class by overriding
existing features Can provide a more appropriate behaviour
To override a method, a sub class must provide exactly the same method signature
SLIDE 93
Polymorphism Using polymorphism
The declared class is a super class of the instance Override the super-class method in the the sub class The method binding is done at runtime
Overriding concrete (non-abstract) methods is generally considered to be bad practice The superclass method is ignored If overriding is necessary, always call the superclass method first
SLIDE 94
a good OO design
is based on
encapsulation inheritance
polymorphism
The Pillars of OO
abstraction
SLIDE 95
Inheritance versus Interfaces Inheritance offers
A clean “is a” relationship Reuse of implementations A contract by declaring some methods as abstract Too much liberty to the clients for overriding superclass methods
An interface offers A contract No reuse of implementations A clean mechanism that ensures that implementing classes will
respect the contract Interface realizations are more robust and flexible, but
tend to be more complex
SLIDE 96
Remarks on Interfaces By using an interface instead of an implementation
directly the design is free to change the way the implementation works As long as the this new way is an respects the Interface
Always try to use the most general type you can Improves flexibility Ensures encapsulation, hiding the implementation
SLIDE 97
Remarks on Types Different types during implementation
The interface is the type used for declaration The implementing class is the type used for instantiation
You cannot instantiate an interface or an abstract class After instantiation, only use the declarative type to perform
operations on it Avoid at all costs to cast to the actual type
This offers the most flexibility and improves robustness
SLIDE 98
Static Members Static members
Operations and properties that apply to the class instead of a class-instance
They have the same behaviour / content for all the instances of a class
Are accessible through the class itself, without instantiation
Static operations have only access to static members (operations / properties)
In UML the property or operation is underlined
SLIDE 99
Responsibility The responsibility of a class is an important concept
A class has one and only one responsibility Defining the responsibility helps to
Consider a class as more than just some data Understand the real impact of what the class may perform, may
mean for the whole concept/domain Responsibility cannot really be drawn in UML
Use a comment in the class rectangle Use a comment in the diagram
Rectangle with right corner flipped and a dashed line to the corresponding class
SLIDE 100
Qualified Associations Qualified associations are used for concepts such as
associative arrays, maps, dictionaries… To translate a n-to-many analysis-association into a n-to-
one design-association The qualifier specifies an unique key, used to select a
specific object of the total set (many-side) Software-implementation view
The instance of the second class always needs the qualifier as argument to his methods
conceptual view A constraint: selection of one instance Usually refers to an attribute of the target class
SLIDE 101
Qualified Association Examples (1) Is drawn as a rectangle appended to the source class The qualifier (Product) says that in the connection with its
class (Order) there is only one instance in the other class (OrderLine)
All access to a given OrderLine requires the qualifier as argument
SLIDE 102
Qualified Association Examples (2) Given a Club object that is linked to a set of Member
objects, how to navigate to one specific Member object?
Look for an unique attribute into the Member class (id) To show this constraint, qualify the Club object using that
unique attribute
SLIDE 103
Bidirectional Associations (1) In bidirectional associations 2 properties are linked
together as inverses Both properties know each other Start at the first, follow the link, get back at the first
Is a problem of synchronization If one property is set to null, how to manage the other side of the
association?
SLIDE 104
Bidirectional Associations (2) Synchronize the bidirectional associations during
implementation Let one side control the relationship
class Car is the master of the relation The other side must reveal some of its data
class Person is the slave Must reveal the way he stores his cars Against the idea of encapsulation Person can never change the way he stores his cars
If a Car is sold or bought, the Car will ask its Person to remove / add ‘him’ from / to the CarList
SLIDE 105
Also known as “link”-classes Used when the association between two classes has
some kind of properties Think about association classes when you have some behaviour
or data that has something to do with a relation between classes but you have no idea which existing class it should be in
Association Class
SLIDE 106
Association Class Example
SLIDE 107
Alternative to Association Class
SLIDE 108
An association class can only be used once An association class must have the same name as the
association An association class is an association!
Association Class Rules
SLIDE 109
Multiple Classification Single classification
Object belongs to a single type That single type can inherit from multiple super-types
Multiple classification Object belongs to several types, implements several interfaces Types are not connected by inheritance
Multiple inheritance (not in Java nor C#) Object is a specification/derivation of several types Those types are connected by inheritance
Generalisation set is disjoint Super-type can only be one of the set Discriminator indicates legal combination
SLIDE 110
Multiple Classification Example (1)
SLIDE 111
Multiple Classifications Example (2) Legal combination
female – patient – nurse Illegal combination
patient – doctor – nurse
SLIDE 112
Template Classes In strongly typed languages, the type of parameters,
return values and attributes are required Bounded arrays have elements of the same type
String [] list = new String[10]; Template classes allow to parametrize those types
Instead of specifying the types of attributes,... the parameter is replaced by actual values to create new classes
Those classes become specialized for the chosen type Used mostly in collections
Define general behaviour Instantiate a specific collection with its containing type
Implemented as Generics in most languages
SLIDE 113
Template Classes Example
SLIDE 114
Template Class Binding <<bind>> indicates the refinement The bound element is
Subtype of the template class No other features are allowed Is always a restriction of the template class
If other features are needed create a subtype of the collection
SLIDE 115
Template Class Examples
SLIDE 116
Unified Modeling Language (UML)
Activity Diagrams
SLIDE 117
Activity Diagram Definition Activity diagrams describe
Procedural Logic - Business Processes - Work Flows All activities can occur in parallel, in any sequence Consists of action and sub-activity states linked together
in the diagram A single action cannot be broken down into subtasks
Cannot be interrupted, once started, it progresses to finish Takes an insignificant amount of time
A sub-activity can be broken into other sub-activity states or actions Depends on the diagram level
SLIDE 118
Actions Actions can have multiple incoming flows
There is an implicit join so an action will take place if and only if all flows trigger
Decompose extensive actions in sub activities Activity can be implemented as
Sub activities of the system
An action, methods of a class
SLIDE 119
Transitions Transitions
Happen whenever a(n) (sub)activity finishes its work Indicate the movement from one state to another
Starting and Ending Initial node Final activity
SLIDE 120
Fork and Join Fork / Join differ depending on their position
Fork splits one incoming flow into multiple concurrent outgoing flows
Join synchronizes multiple flows into one outgoing flow Synchronizing parallel processes
A certain process may not be ended before another A join-fork indicates this constraint The outgoing flow wait until all incoming flows reach the join
Join specifications evaluate all incoming flows Boolean expressions between { } as constraints If all true, proceed with the outgoing flow
SLIDE 121
Conditions Conditional behaviour by decision and merge Decision
One input path, multiple output paths, each provided with a guard expression
2 branches (eventually a decision branch) Only one is processed
Merge Marks the end of the decision Is sometimes omitted if the decision
has a completely different path
SLIDE 122
Swim Lanes The diagram can be partitioned in swim lanes
Used to represent uses cases, classes, roles, ... Each lanes shows exactly who or what is carrying out the
action(s) There is often a connection between swim lanes and
concurrent flows of control
SLIDE 123
Activity Diagram Example (with Swim Lanes)
SLIDE 124
Connections Connections between actions are shown using
Simple lines with open arrow (a Transition) Connector circles Object nodes Lines with pins on both side
SLIDE 125
Transformations Transformations change an output parameter into an
expected input parameter Pins indicate the data that is produced (out) or expected (in)
Used to reinforce the implicit join
SLIDE 126
Asynchronous Calls A signal indicates that the activity receives an event from
an outside process An asynchronous communication between objects
Time
Send
Receive
Receiving activities are listening for external events or waiting for a reply
SLIDE 127
Signals Signals are classifiers that contain information
Have attributes only (information) One implicit operation called “send()”
Allows signals to be sent
SLIDE 128
Asynchronous Example
SLIDE 129
Activity Diagram Example (without Swim Lanes)
SLIDE 130
Unified Modeling Language (UML)
State Diagrams
SLIDE 131
State Diagrams State diagrams describe all the possible states an object
can get into and how the object’s state changes as a result of events that reach the object
State diagrams are drawn for a single class to show the lifetime behaviour of a single object
Use state diagrams for those classes that exhibit interesting behaviour only UI and control objects are popular candidates
SLIDE 132
States A state is a condition or situation during the life of an
object during which it Satisfies some condition, Performs some activity or Waits for some event
An object remains in a state for a finite amount of time
SLIDE 133
State Parts Different parts of a state:
Name: some text A state may be anonymous meaning that it has no name
Internal activities: state reacts to events without transition entry / exit activities: activities executed on entering and exiting the
state respectively do activities: activities executed during the state
Composite states: nested structure of a state, involving disjoint (sequentially active) or orthogonal (concurrently active) sub-states
SLIDE 134
Initial and Final States Initial state indicates the default starting place for the
state machine or composite state Final state indicates that the execution of the state
machine or the enclosing state has been completed Initial and final states are pseudo-states
Neither have the usual parts of a normal state
SLIDE 135
Transitions (1) A transition is a relationship between two states
indicating that An object in the first state will perform certain activities And enter the second state when a specified event occurs and
specified conditions are satisfied On such a change of state, the transition is said to fire
SLIDE 136
Transitions (2) A transition has 5 parts:
Source state: the state affected by the transition If an object is in the source state, an outgoing transition may fire
when the object receives the trigger event of the transition and if the guard condition is satisfied
Target state: the state that is active after the completion of the transition
Trigger-signature [Guard] / Activity Trigger-signature: an event whose reception by the object in the
source state makes the transition legible to fire, providing the guard condition is satisfied
Guard: a boolean expression, evaluated when the transition is triggered by the reception of the event trigger
– If the expression evaluates true, the transition is legible to fire, if the expression evaluates to false, the transition does not fire
– If there is no other transition that could be triggered by the same event, the event is lost
Activity: some behaviour executed during the transition
SLIDE 137
Trigger-signature Syntax
Event-name ‘(‘ comma-separated-parameter-list ‘)’ parameter-name ‘:’ type-expression
Elapsed-time event after(5 seconds) after(10 seconds since exit from state A)
Condition becoming true is shown with the keyword when followed by a boolean expression (continuous test for the condition until it is true)
Transitions without a trigger-signature within their label occur as soon as the activity associated with the state is finished
SLIDE 138
Guard Conditions Boolean expressions enclosed in square brackets and
placed after the trigger event Evaluated only after the trigger event for its transition occurs It is possible to have multiple transitions from the same source
state and with the same event trigger, as long as those conditions do not overlap
Within the boolean expression, it is possible to include conditions about the state of an object
SLIDE 139
Transition Activity Activity is executed if and when the transition fires Activities may include
Operation calls to the object that owns the state diagram or to other visible objects)
Attributes and links of the context object Parameters of the triggering event Activity sequence
SLIDE 140
Example: Access Control Station
SLIDE 141
Example: Air Conditioning
SLIDE 142
Advanced States and Transitions UML state diagrams have some advanced features to
Manage complex behavioural models Reduce the number of states and transitions Codify a number of common and somewhat complex idioms
SLIDE 143
Entry and Exit Activities Dispatch the same activity whenever you enter a state
In the symbol for the state, include an entry activity marked by the keyword event “entry”
Dispatch the same activities whenever you leave a state In the symbol for the state, include an exit activity marked by the
keyword event “exit” Entry and exit activities may not have arguments or guard
conditions
SLIDE 144
State Activities Ongoing activity while the object is in a state, waiting for
an event to occur, i.e., while in a state, the object does some work that will continue until it is interrupted by an event
Use the “do” keyword specifying the work that is to be done inside a state after the entry activity is dispatched
The activity of a “do”-activity might Be a name another state machine Specify a sequence of activities
Regular activities cannot be interrupted, while do-activities can take finite time and can be interrupted by internal activities or transitions (events)
SLIDE 145
Internal Activities Events occurring inside a state but handled without
leaving the state Different than self-transitions!
Self-transition An event triggers the transition, state is left, an activity (if any) is
dispatched, same state is re-entered A self-transition dispatches the state’s exit activity and dispatches
the state’s entry activity Internal activity
If event is triggered, the corresponding activity is dispatched WITHOUT leaving and then re-entering the state
Internal activities may have events with parameters and guard conditions
Internal activities are essentially interrupts
SLIDE 146
Example: Activities
SLIDE 147
Composite States Composite states can be introduced to group a number of
states All sub-states inherit any transition on the composite state The use of composite states makes diagrams often more readable
Orthogonal state diagrams combine different independent states of a given object An object can be in different states simultaneously, each from an
orthogonal region in the diagram
SLIDE 148
Sequential Composite States Sequential composite states are introduced to group a
number of states If the object is in a composite state, it is in only one of its sub-
states at a time (sub-states are disjoint) Transition leading out of a composite state may have its source
the composite state or a sub-state In either case, control first leaves the nested state, then it leaves the
composite state From a source outside a composite state, a transition may target
the composite state or a sub-state If the target is the composite state, this must include an initial state to
which control passes after entering the composite state and after dispatching its entry activity (if any)
If the target is a sub-state, control passes to the sub-state after dispatching the entry activity (if any) of the composite state and then the entry activity (if any) of the sub-states
SLIDE 149
Example: Without Composite States
SLIDE 150
Example: With Composite State
SLIDE 151
Orthogonal Composite States An orthogonal composite state lets you specify two or
more state machines that execute in parallel in the context of the enclosing object If one orthogonal region reaches its final state before the other,
control in that region waits at its final state When both nested regions reach their final state, control from the
two orthogonal regions joins back in one flow Transition to a composite state decomposed into orthogonal
regions: control forks into as many orthogonal flows as there are orthogonal regions
Transition from a composite state decomposed into orthogonal regions: control joins back into one flow If all orthogonal regions reach their final state, or if there is an explicit
transition out of the enclosing orthogonal composite state, control joins back into one flow
SLIDE 152
Example: Orthogonal States
SLIDE 153
Well-Structured State Machine Diagram One state machine represents the dynamic aspects of an
individual object, representing, e.g., an instance of a class or the system as a whole across several use cases
Is simple and therefore should not contain any superfluous states or transitions
Has a clear context and therefore may have access to all the objects visible to its enclosing object
Is efficient and therefore should carry out its behaviour with an optimal balance of time and resources required by the activities it dispatches
Is understandable and therefore should name its states and transitions from the vocabulary of the system
Is not nested too deeply Uses orthogonal composite states sparingly
SLIDE 154
Unified Modeling Language (UML)
Sequence Diagrams
SLIDE 155
Interaction Diagrams Use case diagram is a specification of functional
requirements Analysis classes model the static structure of a system,
based on the functional requirements Next step:
Find classes who realize the behaviour specified in a use case and create an interaction diagram
Emphasize the time-ordered sequence of messages send between objects
SLIDE 156
Sequence Diagrams (1) Collaboration between groups of objects Behaviour of 1 single scenario
Each participant Is named as name:HisClass Has a lifeline
Runs vertically down Orders the messages
from top to bottom can be deleted
Cross at end of lifeline
SLIDE 157
Sequence Diagrams (2) Correlate participants on the diagram
Activation bars Shows activity in the interaction
Sending a message Horizontal line Has an arrow
Receiving an answer Dashed line Names a return-value Has an arrow
SLIDE 158
Sequence Diagrams (3) A sequence diagram does not define algorithms A sequence diagram enables the analyst to see the
responsibilities of the participants Each participant should only have one It delegates to others
SLIDE 159
Example: Centralized Control
SLIDE 160
Example: Distributed Control
SLIDE 161
Loops and Conditions Loops and conditional behaviour are difficult to show
Prefer using an activity diagram Or add a comment with pseudo code
Can be shown using interaction frames All messages belonging to the same flow-control Condition on top Indicate the operation in left corner:
alt-else if-else opt if loop while ref interaction defined in another diagram
SLIDE 162
Example: Loops and Conditions
SLIDE 163
When to Use Sequence Diagrams Behaviour of several objects in same scenario Collaboration among objects Do not to define precise behaviour of methods
State diagram for behaviour of 1 single object Activity diagram for behaviour across many use cases
SLIDE 164
Unified Modeling Language (UML)
Communication Diagrams
SLIDE 165
Communication Diagrams (1) Emphasis is on the data links between the different
participants in the interaction Participants are shown as icons using the same syntax
as in sequence diagrams Arrows indicate messages sent and sequencing is
indicated by numbering the messages The simple numbering scheme shows the overall
sequence The decimal numbering scheme makes clear which
operation is calling which other operation
SLIDE 166
Communication Diagrams (2) Any link drawn is an instance of an association In UML, keywords may be attached to the link end to
indicate various types of implementation: association name parameter (method parameter) local (local variable of a method) global (global variable) self (self link)
Iteration markers (*) and guards can be used to specify control information (as in sequence diagrams)
SLIDE 167
an Access Control Node
a Card
a Customer
a Road Segment
a Trajectory
1. Enter
2. isValid==Valid?
3. accountOK==CheckAccount
4. [isValid And accountOK] New6. ComputeTotal
5. Leave9. PrintInvoice
7. * GetDistance
8. GetUnitPrice
10. UpdateAccount
Example: Access Control Node (1)
SLIDE 168
Example: Access Control Node (2)
an Access Control Node
a Card
a Customer
a Road Segment
a Trajectory
1. Enter
1.1. isValid==Valid?
1.2. accountOK==CheckAccount
1.3. [isValid And accountOK] New2.1. ComputeTotal
2. Leave2.4. PrintInvoice
2.2. * GetDistance
2.3. GetUnitPrice
2.5. UpdateAccount
SLIDE 169
Sequence versus Communication Diagrams Sequence diagrams put more emphasis on the sequence Communication diagrams allow to position objects
corresponding to their static relation Either form is served by simplicity: when representing
much conditional or looping behaviour the techniques break down
When there is a lot of conditional behaviour, it is advisable to use separate diagrams for each scenario
Interaction diagrams are good for looking at the behaviour of several objects within a single use case, they are not good for precise definition of behaviour
SLIDE 170
Well Structured Communication Diagram Is focused on communicating one aspect of a system’s
dynamics Contains only those elements that are essential to
understanding that aspect Provides detail consistent with its level of abstraction and
should expose only those adornments that are essential to understanding
It is not so minimalist that it misinforms the reader about semantics that are important
SLIDE 171
Unified Modeling Language (UML)
Package Diagrams
SLIDE 172
Package Diagrams (1) Used to group elements Useful for classes but, also for other UML elements Packages can have sub-packages Corresponds to
Java package C# namespace
Fully qualified classname in UML: package::subpackage::classname
Façade pattern: public classes with the external interface private classes for the ‘real’ work Only the public classes can be used outside the package
SLIDE 173
Package Diagrams (2) Important issue: how to group the classes? Possibilities:
classes that should need changing for similar reason classes that are reused together look at the dependencies between packages and decide then how
to group the classes Improving the diagram
to control large-scale structure of a system a well-structured system have a clear flow if all dependencies run
in a single direction
SLIDE 174
Remark about Package Dependencies A dependency exists if packages have dependent
classes Changes to a class results in changes to the dependent class
The more dependencies coming into the package, the more stable the package’s interface needs to be
Packages often shows different kinds of structure Structure of application layers Structure of subject areas
SLIDE 175
Package Diagram Example (1)
SLIDE 176
Package Diagram Example (2)
SLIDE 177
Unified Modeling Language (UML)
Deployment Diagrams
SLIDE 178
Deployment Diagram Describes how functionality is distributed across physical
nodes Models the system’s physical architecture as elements
deployed on nodes Node have relationships that model the communication between
nodes Nodes represent computational resources
Two levels of diagrams Descriptor form: artefacts deployed on nodes Instance form: artefact instances deployed on node instances
SLIDE 179
Deployment Diagram Example«device»
Sun V440 4x16GB 192.168.1.24
«executionEnvironment»Solaris 2.9
«executionEnvironment»Apache 4.0
«executionEnvironment»Servlet Engine (Tomcat)
«deployment spec»EJB EAR
«artifact»Customer.jar
«artifact»Order.jar
«artifact»Product.jar
«deployment spec»Web Server WAR
«artifact»Order.jsp
«artifact»Product.jsp
«artifact»Customer.jsp
«device»Sun V490 8x32GB 192.168.1.23
«executionEnvironment»Solaris 2.9
«executionEnvironment»JBoss 5.0
www.EStore.com
«manifest»«manifest»
«manifest»«manifest»
«TCP IP»«TCP IP»
SLIDE 180
Artefacts in Deployment Physical entities in
a software system Executable files Libraries Jar files Documents
May show physical manifestation for one or more components
SLIDE 181
Unified Modeling Language (UML)
Position and History of UML
SLIDE 182
History (1) Object Management Group (OMG)
http://www.omg.org/
Open membership, non-profit consortium that produces and maintains computer industry specifications for interoperable enterprise applications
Formed to built standards for interoperability Model Driven Architecture (MDA) is based on the
modeling specifications specified in Meta-Object Facility ™ (MOF) Unified Modeling Language™ (UML) XML Metadata Interchange (XMI®) Common Warehouse Metamodel ™ (CWM)
SLIDE 183
History (2) 1980
Objects used in Smalltalk and C++ 1988 – 1992
Key books about OO graphical modeling languages First attempt to standardization failed 1995
Jim Rumbaugh (GE) joins Grady Booch (Rational) creating the Unified Method 0.8
Ivar Jacobson joins the Rational-team
SLIDE 184
History (3) Commercial motives urge to create a unified graphical
language that allow CASE tools to freely exchange models
OMG input becomes more explicit 1997
First use of the name ‘Unified Modeling Language’ releasing UML 1.0
UML 1.2: first official standard 2001
1.4 2002
1.5 2003
UML 2.0: current official version
SLIDE 185
UML Definition (1) Standard for graphical modelling of software Facilitates discussions about design Models
The structure, behaviour, and architecture of an application The business processes and data structure
A model abstracts the essential details of the underlying problem
Used in different ways by different people
SLIDE 186
UML Definition (2) UML defines a notation
The graphical syntax For instance, a class diagram notation defines how items and
concepts (a class, an association, ...) are represented They appeals to intuition, rather than to formal definition (what
exactly is a class, an association…)
UML defines a meta-model UML has been defined in “UML” A diagram defines the concepts of the language
SLIDE 187
UML Definition (3) All lines, squares… are part of the graphical notation The whole is a small piece of the UML meta-model
SLIDE 188
Rules When Using UML Prescriptive language rules
Controlled by official body To follow strictly!
Descriptive language rules By convention As other people use the language
Any information can be suppressed for a particular diagram This does not mean that the information is non-existent
SLIDE 189
Sketching Diagrams Sketching
The emphasis is on selective communication rather than complete specification
Informal and dynamic Helps to communicate ideas and alternatives Needs little time Whiteboard as tool
SLIDE 190
Blueprints Built by designer
All design decisions are laid out A detailed design for the programmer to code up Sophisticated tools handle the details CASE-tools (Computer Aided Software Engineering) Some tools perform forward and/or reverse engineering
Forward engineering: UML to code Reverse engineering: code to UML
This automates building the system
SLIDE 191
Programming Language As soon as the system can be completely specified by
UML UML can become the programming language UML “is” the source code
UML diagrams are compiled directly to executable code No forward nor reverse engineering, since the diagram is
the code
SLIDE 192
Non-UML Diagrams (1) Navigation Diagram
SLIDE 193
Non-UML Diagrams (2) Decision table
CRC cards
SLIDE 194
Why Using UML (1) Programming languages are not at the highest level of
abstraction Too detailed Difficult to discuss about
A good design, without all the details, helps to communicate ideas
Can be used for software logic ... UML elements map directly to software elements
… and for business logic UML represents a description of the concepts of a domain
SLIDE 195
Why Using UML (2) Large enterprise applications must be structured
Scalability - Security - Robustness Their structure / architecture, must be defined clearly
A way of dealing with complexity Enables code reuse
Using a model before starting with implementing Makes sure business functionality is complete and correct Makes sure the end-user needs are met Supports requirements for scalability, robustness, security,
extendibility, and other characteristics
SLIDE 196
The Importance of UML Engineering example:
Architects design buildings Builders use designs to create buildings The more complicated the building, the more critical the
communication between architect and builder Blueprints are the standard graphical language that both
architects and builders must learn as part of their trade
Writing software is not completely unlike constructing a building
UML gives everyone from business analyst to designer to programmer a common vocabulary to talk about software design
SLIDE 197
MDA (1) Model Driven Architecture is a standard approach to
using UML as a programming language UML models can be exchanged with other MDA
compliant environments PIM (Platform Independent Model)
Created by a designer UML model independent of any technology Business functionality and behaviour, no technical aspects
PSM (Platform Specific Model) One or more generated from the PIM, one for each target platform
that the developer chooses Generated by a tool Model of a system targeted to a specific execution environment Contains the same information as an implementation, but in the
form of an UML model instead of running code
SLIDE 198
MDA (2) Tools can generate code for that platform
Along with other necessary files Definition files, configuration files, makefiles, build files, and other file
types The developer can hand-tune the generated code The tool executes the makefiles / builds to produce a deployable
final application
SLIDE 199
MDA (3) MDA applications are composable
PIMs for modules, services, or other MDA applications can generate calls using whatever interfaces and protocols are required
MDA applications are future-proof When a new "Next Best Thing" comes on the market, OMG
members will generate and standardize a mapping to it The vendor will upgrade his MDA enabled tool to include it Generate cross-platform invocations to the new platform, even
automatically porting existing MDA applications to it using the existing PIMs
SLIDE 200
MDA (4) The process of gathering and analyzing an application's
requirements, and incorporating them into a program design, is a complex one
The industry currently supports many methodologies that define formal procedures http://www.cetus-links.org/oo_ooa_ood_methods.html Object-orientation is only one of them
The model abstracts the essential details of the underlying problem from its usually complicated real world
UML is methodology-independent
SLIDE 201
Iterative Methodology The iterative style breaks down a project by subsets of
functionality
Per subset, the complete software life cycle is done: Analysis, design, code and test Result is a production-ready integrated software after each cycle
The project will have multiple releases
SLIDE 202
Waterfall The waterfall process breaks down a project based on
activity Analysis, design, coding and testing
An activity is completely finished before an other activity begins
In practice, there can be back-flows (making it iterative) During coding, revisit the analysis and / or design
SLIDE 203
Staged Delivery Staged delivery is a combination of waterfall and iterative
process
Analysis and high-level design Will be done first, seen as activities Happen in waterfall style
Coding and testing Comes afterwards Divided up into iterations
SLIDE 204
Development Process Some form of iterative process is in favour Provides better control over the evolution of the total
project Every functionality is / should be completed The iterative style explicitly assumes rework
Reworking or deleting code during a later iteration of the project Being iterative is being flexible to possible changes This rework is not a waste, tools can help
Automated regression tests Refactoring techniques Continuous integration
SLIDE 205
Predictive Planning Predictive planning has two stages
Plan the work Difficult to predict how long this takes...
Do the analysis, coding, testing…
Are software projects predictable? Requirements are often misunderstood Requirements change often before the project is finished
Solution Freezing the requirements early, not permitting changes But put more efforts into the requirements aspects
SLIDE 206
Adaptive Planning Adaptive planning sees predictability as an illusion Treats changes as a constant in a software project Controls / plans the project without doing any prediction
of its evolution The plan is a baseline to assess the consequences of
change rather than as a prediction of the future
SLIDE 207
From Process to Project (1) Each project assumes another approach There is not “the one” process for that project The chosen process depends on
The used technology Size and distribution of the team Nature of the risks Consequences of failure Culture of the organization ...
SLIDE 208
From Process to Project (2) The iteration retrospective considers
How things went How things can be improved
At the end of each iteration Keep what is working fine Discuss what went wrong
Project retrospective takes place at the end of the project or at a major release
The practice of looking back to move forward Learn from the experience and plan changes for the next
effort http://www.retrospectives.com/
SLIDE 209
From UML to Process How UML is fitted into the process depends on how UML
diagrams are used: To help communicate about ideas (sketches) To feed a complex CASE tool (blueprint or programming
language) Or as documentation for later
Major phases during which UML can be used Requirements analysis Design and development Documentation
SLIDE 210
From UML to Requirements Requirements analysis tries to figure out what the users
and customers want Make sure users / customers understand the diagrams Use cases
Describe how people interact with the system Class diagram (conceptual perspective)
Rigorous vocabulary of the domain Activity diagrams
Show how software and human activities interact State Machine diagrams
Used for concepts with a interesting life cycle
SLIDE 211
From UML to Design UML used for design, more precise about notations Class diagram (software perspective)
Classes and how they interrelate Sequence diagram
Most important scenario’s from use cases Package diagram
Large-scale organization of the software State diagram
Classes with complex life cycle Deployment diagram
Physical layout of the software
SLIDE 212
From UML to Documentation Once software is built, UML is used to document the
project UML diagrams for getting an overall understanding
No detailed information on the code As sketches for the reader to understand the principles of the
system Package diagram
As road map of the system Deployment diagram
High-level physical structure Class diagram
Graphical view of package contents State Machine diagram
For a complex life cycle behaviour of a class