Anda di halaman 1dari 161

UML

Fundamentals
Ing. Gerardo Padilla Zárate

Day 4
Course Outline
1. Course presentation P
2. OO Concepts Review P
3. Introduction to UML P
4. UML Views P
5. Tool Fundamental P
Course outline (cont..)
6. Structural diagrams P
7. Behavioral Diagram P
8. Model Management Diagrams
9. UML during development process
10. UML and 4GL
11. Review and Critique
Review
Use Case Diagrams
Use Case
n A use case is a kind of classifier representing a
coherent unit of functionality provided by a
system, a subsystem, or a class as manifested
by sequences of messages exchanged among
the system (subsystem, class) and one or more
outside interactors (called actors) together with
actions performed by the system (subsystem,
class).
Use Case Diagram
n Use case diagrams show actors and use
cases together with their relationships.
The use cases represent functionality of a
system or a classifier, like a subsystem or
a class, as manifested to external
interactors with the system or the
classifier.
Actor
n A coherent set of roles that users of use
cases play when interacting with these use
cases.
n An actor has one role for each use case
with which it communicates.
Use Case Diagram
Telephone Catalog

Check
status

Place Salesperson
order

Fill orders

Customer Shipping Clerk

Establish
credit

Supervisor
Use Case Relationships
Relationship Association
n The participation of an actor in a use case;
that is, instances of the actor and
instances of the use case communicate
with each other.
n This is the only relationship between
actors and use cases.
Use Case Relationships: Association
Relationship Include
n An include relationship from use case E to
use case F indicates that an instance of
the use case E will also contain the
behavior as specified by F.
n The behavior is included at the location
which defined in E.
Use Case Relationships
Relationship Extends
n An extend relationship from use case A to
use case B indicates that an instance of
use case B may be augmented (subject to
specific conditions specified in the
extension) by the behavior specified by A.
n The behavior is inserted at the location
defined by the extension point in B, which
is referenced by the extend relationship.
Use Case Relationships
Relationship Generalization
n A generalization from use case C to use
case D indicates that C is a specialization
of D.
Actor Relationships
1 * Place
Order
Salesperson

Establish
1 *
Credit
Supervisor
Use Case Description: Change Flight
nActors: traveler, client account db, airline reservation system
nPreconditions:

• Traveler has logged on to the system and selected ‘change flight


itinerary’ option
nBasic course
• System retrieves traveler’s account and flight itinerary from client
account database
• System asks traveler to select itinerary segment she wants to
change; traveler selects itinerary segment.
• System asks traveler for new departure and destination
information; traveler provides information.
• If flights are available then

• …

• System displays transaction summary.

nAlternative courses
• If no flights are available then …
When to model use cases
n Model user requirements with use
cases.
n Model test scenarios with use cases.
n If you are using a use-case driven
method
¨ start with use cases and derive your
structural and behavioral models from it.
n If you are not using a use-case driven
method
¨ make sure that your use cases are consistent
with your structural and behavioral models.
Use Case Modeling Tips
n Make sure that each use case describes a significant chunk
of system usage that is understandable by both domain
experts and programmers
n When defining use cases in text, use nouns and verbs
accurately and consistently to help derive objects and messages
for interaction diagrams
n Factor out common usages that are required by multiple use
cases
¨ If the usage is required use <<include>>
¨ If the base use case is complete and the usage may be optional,
consider use <<extend>>
n A use case diagram should
¨ contain only use cases at the same level of abstraction
¨ include only actors who are required
n Large numbers of use cases should be organized into packages
Online HR System: Use Case Relationships
Online HR System: Update Benefits Use Case
nActors : employee, employee account db, healthcare plan system,
insurance plan system
nPreconditions:

•Employee has logged on to the system and selected ‘update benefits’


option
nBasic course
• System retrieves employee account from employee account db
•System asks employee to select medical plan type; include Update
Medical Plan.
• System asks employee to select dental plan type; include Update
Dental Plan.
• …

nAlternative courses
• If health plan is not available in the employee’s area the employee is
informed and asked to select another plan...
Review: Use Case Diagrams
n What is a use case?
n What is a collaboration diagram?
n Describe the relation between Sequence
Diagram and Collaboration Diagram.
Excercise 7
Excercise 7
Model Management Diagrams
n Packages
n Subsystem
n Model
Package
n A package is a grouping of model
elements. Packages themselves may be
nested within other packages.

n All kinds of UML model elements can be


organized into packages.
Package

A package is a grouping of model elements


Package – Example
Sales

Customer Order

Warehouse

Location Item

Stock Item Order Item


Core Concepts
Construct Description Syntax
Package A grouping of model elements.
Name

Import A dependency indicating that the «import»


public contents of the target
package are added to the namespace
of the source package.
Access A dependency indicating that the «access»
public contents of the target
package are available in the
namespace of the source package.
Visibility
n Each contained element has a visibility
relative to the containing package
¨ A public element is visible to elements outside the
package, denoted by ‘+’
¨ A protected element is visible only to elements
within inheriting packages, denoted by ‘#’
¨ A private element is not visible at all to elements
outside the package, denoted by ‘-’
n Same syntax for visibility of attributes and
operations in classes
Import
X Y

B +C
-D
«import»
A +E

X Y

B Y::C +C
-D
«import»
A Y::E +E

The associations are owned by package X


Access
X Y

B +C
-D
«access»
A +E

X Y
«access»

B +C
-D

A +E

The associations are owned by package X


Diagram Tour
n Packages are shown in static diagrams
n Two equivalent ways to show containment:
When to Use Packages

n To create an overview of a large set


of model elements
n To organize a large model
n To group related elements
n To separate namespaces
Modeling Tips – Package
n Gather model elements with strong cohesion
in one package
n Keep model elements with low coupling in
different packages
n Minimize relationships, especially
associations, between model elements in
different packages
Model Management Diagrams
n Packages
n Subsystem
n Model
Subsystem
n A grouping of model elements that
represents a behavioral unit in a physical
system.
n A subsystem offers
¨ interfaces and has operations.
n In addition, the model elements of a
subsystem can be partitioned into
specification and realization elements.
Subsystem

Subsystems are used for


system decomposition
Subsystem – Example

Traffic
Trunk Control

Communicating subsystems
constitute a system

Subscription
Subsystem Aspects
n A subsystem has two aspects:
¨ An external view, showing the services
provided by the subsystem
¨ An internal view, showing the
realization of the subsystem
n There is a mapping between the two
aspects
Subsystem Aspects
Specification elements Realization elements

A subsystem has a specification and a realization


to represent the two views
Subsystem Realization
Specification elements Realization elements

?
n The subsystem realization defines the actual contents
of the subsystem
n The subsystem realization typically consists of classes and
their relationships, or a contained hierarchy of subsystems
with classes as leaves
Subsystem Specification

Specification elements Realization elements

?
The subsystem specification defines the
external view of the subsystem
Subsystem Specification
n The subsystem specification
¨ describes the services offered by the
subsystem
¨ describes the externally experienced
behavior of the subsystem
¨ does not reveal the internal structure of
the subsystem
¨ describes the interface of the subsystem
Specification Techniques
n The Use Case approach
n The State Machine approach
n The Logical Class approach
n The Operation approach

…and combinations of these.


Use Case Approach
Specification elements Realization elements

n For subsystem services used in certain sequences


n When the specification is to be understood by non-
technical people
Use Case Approach – Example
Traffic Control
Specification elements Realization elements

Operator Change Digit Analysis Information

Initiate Call

Trunk
Receive Digit and Connect

Subscription Hook Signal and Disconnect


State Machine Approach
Traffic Control
Specification elements

Stopped Running

Maintenance

Error Exhausted

n For subsystems with state dependent behavior


n Focuses on the states of the subsystem and the
transitions between them
Logical Class Approach
Traffic Control
Specification elements

Number
Analyzer Dictionary

Network
Manager

n When usage of the subsystem is perceived as


manipulation of objects
n When the requirements are guided by a particular
standard
Operation Approach
Traffic Control
Operations
initiateConnection (…)
dialledDigit (…)
throughConnect (…)
bAnswer (…)
bOnHook (…)
aOnHook (…)

n For subsystems providing simple, “atomic” services


n When the operations are invoked independently
Mixing Techniques
Traffic Control
Specification elements
Operations
changeDigitAnalysisInformation (...)

Specification elements

Initiate Call

Trunk
Receive Digit and Connect

Subscription Hook Signal and Disconnect


Complete Subsystem Notation
Operations Realization elements

Specification elements

n The complete subsystem symbol has three pre-defined


compartments
n Each of the compartments may be optionally omitted
from the diagram
Subsystem Interfaces

Traffic
Trunk Control Subscription

Traffic
Trunk Control Subscription
Operations and Interfaces
«Interface» «Interface»
Operations
operation1( ) operation2( )
operation2( ) «realize» operation1( ) : Type1 «realize» operation3( )
operation4( ) operation5( )
operation2( ) : Type2

operation3( ) : Type3
operation4( ) : Type4

operation5( ) : Type5

The subsystem must support all operations in the


offered interfaces
Subsystem Interfaces
«Interface» «Interface»
Specification elements
«realize» «realize»

An interface operation may alternatively be supported


by a specification element of the subsystem
Specification – Realization
n The specification and the realization
must be consistent
n The mapping between the
specification and the realization can
be expressed by:
¨ realization relationships
¨ collaborations
Realize Relationship
Operations Realization Elements
operation1( ) : Type1 «realize»
operation1( )
operation2( ) : Type2

operation3( ) : Type3
operation4( ) : Type4

operation5( ) : Type5

Realization is particularly useful in simple mappings


Realize – Example
Traffic Control
Operations Realization elements
changeDigitAnalysisInformation ( )

«realize»
Specification elements

Initiate Call
changeDigitAnalysisInformation ( )
:
:
Trunk
Receive Digit and Connect

Subscription Hook Signal and Disconnect


Collaboration
n A collaboration defines the roles to be played
when a task is performed
n The roles are played by interacting instances

Sequence Diagram Collaboration Diagram


2: dialledDigit
:Trunk :Traffic Control :Subscription 3: dialledDigit
6: bAnswer
markBusy :Traffic Control
dialledDigit 4: throughConnect
dialledDigit
:Trunk
throughConnect
markBusy

bAnswer :Subscription
1: markBusy
5: markBusy
Subsystem Interaction

4:receive

1:transmit
2:send

3:ack

1.4
Communicating with
Subsystems
n Two approaches:
¨ Open subsystem - public elements are
accessed directly
¨ Closed subsystem - access via the
subsystem itself

1.4
Open Subsystems
Traffic Control

n A subsystem is called
-B
open if its realization
+A is used directly by the
environment
«import»
n The specification
Trunk
acts
+TC::A ¨ as an overview of
the subsystem
-C ¨ as a requirements
specification
+B

1.4
Closed Subsystems
Traffic Control

+A n A subsystem is called closed


if its realization is not directly
-B used by the environment

n The specification acts


¨ as an overview of the
Trunk subsystem
¨ as a requirements
-C specification
¨ as a specification of
+B
how to use the
subsystem

1.4
Subsystem Instance

:Traffic Control

A subsystem instance is the runtime


representation of a subsystem. Its task is
to handle incoming stimuli.

1.4
Diagram Tour
n Subsystems can be shown in static diagrams and
interaction diagrams
n “Fork” notation alternative for showing contents:

Specification elements Realization elements

Realization elements
Diagram Tour – continued
n Subsystems can be shown in interaction diagrams
¨ collaboration diagrams
¨ sequence diagrams

Sequence Diagram
When to Use Subsystems
n To express how a large system is
decomposed into smaller parts
n Distributed development
n To express how a set of modules are
composed into a large system
n For component based development
Component Based Development
ShoppingCart

Specification Elements Realization Elements

«Interface» ShoppingCart
ShoppingCartHome «auxiliaryClass» Home «focalClass»
«call»
HomeObject ShoppingCart ShoppingCart
create(…)
«call» Impl
findByPrimaryKey(…)
...
ArtStore «auxiliaryClass»
«call»
Client «Interface» Context
ShoppingCart
ShoppingCart DBbroker
«call» getItemCount(…)
«auxiliaryClass» «auxiliaryClass»
setItemCount(…)
getTotal(…) RemoteObject ContextObject
setTotal(…)
...

An EJB component modeled using a subsystem and classes


stereotyped «focalClass» or «auxiliaryClass»

1.4
Modeling Tips – Subsystem
n Define a subsystem for each separate
part of a large system
n Choose specification technique
depending on factors like kind of system
and kind of subsystem
n Realize each subsystem independently,
using the specification as a
requirements specification
Model Management Diagrams
n Packages
n Subsystem
n Model
Model

A model captures a view of a system, with a certain


purpose. It is a complete description of those
aspects of the system relevant to the purpose of the
model, at the appropriate level of detail.
Model – Example
Use Case Model

Design Model
Core Concepts
Construct Description Syntax
Model A view of a system, with a certain
purpose determining what aspects Name
of the system are described and at
what level of detail.

Trace A dependency connecting model «trace»


elements that represent the same
concept within different models.
Traces are usually non-directed.
Trace
Analysis

Design

«trace»
Diagram Tour
n Models as such are seldom shown in diagrams
n Two equivalent ways to show containment:
Model vs. Diagram
Diagrams make up the
Use Case
documentation of a model
Model

Design
Model
When to Use Models
n To give different views of a system
to different stakeholders
n To focus on a certain aspect of a
system at a time
n To express the results of different
stages in a software development
process
Modeling Tips – Model

n Define the purpose for each model


n A model must give a complete picture of
the system, within its purpose
n Focus on the purpose of the model;
omit irrelevant information
Models and Subsystems
Models and subsystems can be combined in hierarchies:
Wrap Up Model Management
n Packages are used to organize a large
set of model elements
¨ Visibility
¨ Import
¨ Access
n Subsystems are used to represent
parts of a system
¨ Specification
¨ Realization
n Models are used to capture different
views of a system
¨ Trace
Excercise 8
UML during
Development Process
Unified Process (minimum elements)

n Use Case Model


n Use Case Analysis
n Architecture Analysis
n Use Case Design
n Class Design
n Architecture Design
n Subsystem Design
n Table Design
n Relations and Referential Integrity
UML and 4GL

Based on paper entitled:


Designing Procedural 4GL Applications
through UML Modeling
The paper (Abstract)
n Presents a Unified Modeling Language (UML) model for
VisualAge Generator (VG) business-oriented
applications.
n This model was defined to bridge between two different
models, the object-oriented UML design model and the
VG programming model, which use a procedural high-
level 4GL.
n This tool provides developers with the ability to create a
UML model for VG applications, check its compatibility,
and generate the appropriate VG 4GL entities. The
paper describes a methodology of the design process for
a sample application.
n The proposed VG UML Model includes a set of entities, presented
by UML classes with special VG-oriented stereotypes, and the UML
relationships between them.
n Most of these entities are either based on VG 4GL parts or
encapsulate them. Through the analysis of the VG application
structure we found that encapsulating 4GL data entities and the
related function entities into objects can be beneficial to the design
process. We define Program objects to be based on the 4GL
program part that holds the computation units of the VG application.
In addition, we introduce other types of objects, such as the
ExternalObject (based on 4GL SQL records) and the ViewObject
(based on TUI Maps or Web UI records), which encapsulate data
with the related functions required for access.
UML and more
UML more
n Extension mechanism
n OCL
n Profiles
Ideas to Take Away
n UML is effective for modeling large, complex
software systems
n It is simple to learn for most developers, but
provides advanced features for expert analysts,
designers and architects
n It can specify systems in an implementation-
independent manner
n 10-20% of the constructs are used 80-90% of the
time
n Structural modeling specifies a skeleton that can be
refined and extended with additional structure and
behavior
n Use case modeling specifies the functional
requirements of system in an object-oriented manner
Extension mechanism
and profiles
Semantic Variations in UML
n UML contains semantic aspects that are:
¨ undefined (e.g., scheduling discipline), or
¨ ambiguous (multiple choices/interpretations)
n Why is this the case?
¨ UML can’t address every domain perfectly
¨ Different domains require different specializations
n But, if UML can be extended in arbitrary
ways, what is the value of having a standard?
UML as a “Family of Languages”

n The standard can be specialized for different domains


¨ in effect: refinements of the standard

UML 1.4 Standard Using


extensibility
mechanisms

UML for Real Time UML for CORBA etc.


Extensibility Mechanisms
n Extensibility Mechanisms
¨ AllowModelers to refine the semantics of
UML for a specific domain
n Extensions cannot violate the standard
UML semantics
¨ Enforces a consistent core of concepts and
semantics for every variation
¨ Prevents meta-model explosion (Using UML
to model everything and anything)
How UML Extensibility Works
n The standard UML semantics can be
viewed as defining a space of possible
interpretations

refined semantics
(valid) different semantics
(NOT valid)
Standard UML semantics
Models
n A model is a description of something
¨ “a pattern for something to be made” (Merriam-
Webster)

blueprint
(model)

building building

n model ≠ thing that is modeled


¨ The Map is Not The Territory
Meta-Models
n Are Simply Models of Models
<sawdust>
<2 tons>
<lard>
<Ben&Jerry’s>
<5 tons> Objects (M0)

Customer CustomerOrder
item Model (M1)
id
quantity

Class Association Meta-Model (M2)


The UML Meta-Model
n Is a UML Model of UML
Meta--Class
Meta
GeneralizableElement
isRoot : Boolean Feature
isLeaf : Boolean
isAbstract : Boolean visibility : {public, private,
protected}

*
Classifier

Well--formedness constraint (OCL)


Well

not self.isAbstract implies


self.allOperations->forAll(op |
Class
self.allMethods->exists(m |
isActive : Boolean m.specification includes (op)))
The UML Meta-Model
n Put another way, UML uses (a part of)
itself as a Meta-language
¨ Other examples: Scheme, Lisp, Smalltalk
n This small subset of UML is used to
describe all of UML
¨ The subset contains classes, associations,
operations, constraints, generalization, etc.
¨ This core subset is related to MOF (more on
MOF in Part 4)
The Basic Extensibility
Mechanisms
n Stereotypes
¨ used to refine meta-classes (or other stereotypes) by
defining supplemental semantics
n Constraints
¨ predicates (e.g., OCL expressions) that reduce
semantic variation
¨ can be attached to any meta-class or stereotype

n Tagged Values
¨ individual modifiers with user-defined semantics
¨ can be attached to any meta-class or stereotype
Stereotypes
n Used to define specialized model elements based on a
core UML model element
n Defined by:
¨ Base metaclasses (or stereotype)
n What element is specialized?
¨ Constraints:
n What is special about this stereotype?
¨ required tags (0..*)
n What values does this stereotype need to know?
¨ icon
n How should I appear in a model?
n A model element can be stereotyped in multiple different
ways

1.4
Example
n Capsule: A special type of concurrent
object used in modeling certain real-
time systems
n By definition, all classes of this type:
¨ are active (concurrent)
¨ have only features (attributes and operations) with
protected visibility
¨ have a special “language” characteristic used for
code generation purposes
n In essence, a constrained form of the
general UML Class concept
Example: Stereotype Definition
Stereotype Base Class Tags Constraints
n Using a tabular form:
isActive = true;
self.feature->select(f |
«capsule» Class language f.oclIsKindOf(Operation))->
forAll(o |
o.elementOwnership.visibility
= #protected)

Tag Stereotype Type Multiplicity


language «capsule» String 0..1

1.4
Stereotype Notation Stereotype
icon
n Several choices
«capsule»
aCapsuleClass aCapsuleClass

(a) with guillemets (b) with icon


(“gwee-mays”)

(c) iconified form


Extensibility Method
n Refinements are specified at the Model (M1) level but apply to the
Meta-Model level (M2)
¨ avoids need for “meta-modeling” CASE tools
¨ can be exchanged with models
«capsule»
aCapsuleClass

Customer CustomerOrder «Capsule»


id item (M1)
quantity

Class Association (M2)


Graphical Definition
n Alternative to the tabular form
¨ defined in a user (M1) model
«metaclass»
Class

«stereotype»

«stereotype»
capsule
Tags
language : String

1.4
Heuristic: Combining Stereotypes
n Through multiple inheritance:
«stereotype»
capsule «metaclass»
Package
Tags
language : String

«stereotype»

«stereotype»
PackageCapsule

1.4
When to Use Stereotypes?
n Why not use normal subclassing instead?
n Use stereotypes when:
¨ additionalsemantic constraints cannot be
specified through standard M1-level modeling
facilities
n e.g. “all features have protected visibility”
¨ theadditional semantics have significance
outside the scope of UML
n e.g. instructions to a code generator
“debugOn = true”
Tagged Values
n Consist of a tag and value pair
n Typed with a standard data type or M1 class
name
n Typically used to model stereotype attributes
¨ Additional information that is useful/required to
implement/use the model
n May also be used independently of stereotypes
¨ e.g., project management data
(“status = unit_tested”)

1.4
Constrains
n Constraints
¨ formal or informal expressions
¨ must not contradict inherited base semantics

ATM_Withdrawal Account

customer : id customer : id
amount : Money balance : Money
{amount is multiple of $20}

«constraint»
{ATM_Withdrawal.customer =
Account.customer}
UML Profiles
n A package of related extensibility elements
that capture domain-specific variations
and usage patterns
¨A domain-specific interpretation of UML
n Profiles currently being defined by the
OMG:
¨ EDOC
¨ Real-Time
¨ CORBA
¨ ...
OCL

Object Constraint Language


Overview
n What are constraints?
n Core OCL Concepts
n Advanced OCL Concepts
n Wrap up
Why use OCL ?
What’s in it
for me?

Use the
Object
Constraint
Language
Can we make this more
precise?
flights 1
Flight Airplane
0..*

0..*
PassengerFlight CargoFlight
0..*
1
PassengerPlane CargoPlane
1

116
Diagram with added invariants

Flight 0..* 1 Airplane


type : flights type :
enum of cargo, passenger enum of cargo, passenger

{context Flight
inv: type = #cargo implies airplane.type = #cargo
inv: type = #passenger implies airplane.type = #passenger}

117
Definition of constraint
n “A constraint is a restriction on one or
more values of (part of) an object-oriented
model or system.”
Different kinds of constraints
n Class invariant
¨a constraint that must always be met by all
instances of the class
n Precondition of an operation
¨a constraint that must always be true
BEFORE the execution of the operation
n Postcondition of an operation
¨a constraint that must always be true AFTER
the execution of the operation
Constraint stereotypes
n UML defines three standard stereotypes
for constraints:
¨ invariant
¨ precondition
¨ postcondition
What is OCL?
n OCL is
¨a textual language to describe constraints
¨ the constraint language used in UML models
n As well as the UML meta-model
n Formal but easy to use
¨ unambiguous
¨ no side effects
Constraints and the UML model
n OCL expressions are always bound to a
UML model
¨ OCL expressions can be bound to any model
element in UML
Core OCL Concepts
n What are constraints
n Core OCL Concepts
n Advanced OCL Concepts
n Wrap up
Example model
Flight
departing
origin Flights
Airport departTime: Time
* /arrivalTime: Time flights
name: String duration : Interval
* maxNrPassengers: Integer
arriving * airline
desti-
nation Flights Airline

passengers * {ordered} name: String

Passenger

$minAge: Integer
age: Integer airline 0..1
needsAssistance: Boolean 0..1

book(f : Flight) CEO


Constraint context and self
n Every OCL expression is bound to a
specific context.
¨ The context is often the element that the
constraint is attached to
n The context may be denoted within the
expression using the keyword ‘self’.
¨ ‘self’
is implicit in all OCL expressions
¨ Similar to`this’ in C++
Notation
n Constraints may be denoted within the UML
model or in a separate document.
¨ the expression:
context Flight inv: self.duration < 4
¨ is identical to:
context Flight inv: duration < 4
¨ is identical to:
Flight

<<invariant>> duration: Integer


duration < 4
Elements of an OCL expression
n In an OCL expression these elements may
be used:
¨ basic types: String, Boolean, Integer, Real.
¨ classifiers from the UML model and their
features
n attributes, and class attributes
n query operations, and class query operations (i.e.,
those operations that do not have side effects)
¨ associations from the UML model
Example: OCL basic types

context Airline inv:


name.toLower = ‘klm’

context Passenger inv:


age >= ((9.6 - 3.5)* 3.1).floor implies
mature = true
Model classes and attributes
n “Normal” attributes
context Flight inv:
self.maxNrPassengers <= 1000

n Class attributes
context Passenger inv:
age >= Passenger.minAge
Example: query operations
context Flight inv:
self.departTime.difference(self.arrivalTime)
.equals(self.duration)
Time Interval
$midnight: Time nrOfDays : Integer
month : String nrOfHours : Integer
day : Integer nrOfMinutes : Integer
year : Integer
hour : Integer equals(i:Interval):Boolean
minute : Integer $Interval(d, h, m : Integer) :
difference(t:Time):Interval Interval
before(t: Time): Boolean
plus(d : Interval) : Time
Associations and navigations
n Every association in the model is a
navigation path.
n The context of the expression is the
starting point.
n Role names are used to identify the
navigated association.
Example: navigations departing
Flight
origin Flights
Airport departTime: Time
* /arrivalTime: Time
name: String duration : Interval
* maxNrPassengers: Integer
desti- arriving
nation Flights

context Flight
inv: origin <> destination
inv: origin.name = ‘Amsterdam’

context Flight
inv: airline.name = ‘KLM’
Association classes
context Person inv:
if employer.name = ‘Klasse Objecten’ then
job.type = #trainer
else
job.type = #programmer
Job
endif type : {trainer, programmer}

* 1 Company
Person
employee employer name : String
The OCL Collection types
n What are constraints
n Core OCL Concepts
¨ Collections

n Advanced OCL Concepts


n Wrap up
Significance of Collections in OCL
n Most navigations return collections rather
than single elements
Flight 0..* 1 Airplane
type : flights type :
enum of cargo, passenger enum of cargo, passenger
Three Subtypes of Collection
n Set:
¨ arrivingFlights(from
the context Airport)
¨ Non-ordered, unique
n Bag:
¨ arrivingFlights.duration (from the context
Airport)
¨ Non-ordered, non-unique
n Sequence:
¨ passengers (from the context Flight)
¨ Ordered, non-unique
Collection operations
n OCL has a great number of predefined
operations on the collection types.
n Syntax:
¨ collection->operation

Use of the “->” (arrow)


operator instead of the
“.” (dot) operator
The collect operation
n Syntax:
collection->collect(elem : T | expr)
collection->collect(elem | expr)
collection->collect(expr)
n Shorthand:
collection.expr
n The collect operation results in the collection of
the values resulting evaluating expr for all
elements in the collection
n Shorthand often trips people up. Be Careful!
Example: collect operation
context Airport inv:
self.arrivingFlights -> collect(airLine) ->notEmpty
f1
airp1
airline1
f2

f3 airline2

airp2 f4
airline3
f5

departing flights arriving flights


The select operation
n Syntax:
collection->select(elem : T | expression)
collection->select(elem | expression)
collection->select(expression)

n The select operation results in the subset


of all elements for which expression is true
Example: collect operation
context Airport inv:
self.departingFlights->select(duration<4)->notEmpty
f1
duration = 2
airp1
f2
airline1
duration = 5

f3
duration = 3 airline2

f4
airp2
duration = 5
airline3
f5
departing flights duration = 2

arriving flights
The forAll operation
n Syntax:
¨ collection->forAll(elem : T | expr)
¨ collection->forAll(elem | expr)
¨ collection->forAll(expr)

n The forAll operation results in true if expr


is true for all elements of the collection
Example: forAll operation
context Airport inv:
f1
self.departingFlights->forAll(departTime.hour>6)
depart = 7
airp1
f2
airline1
depart = 5

f3
depart = 8 airline2

f4
airp2
depart = 9
airline3
f5
depart = 8

departing flights arriving flights


The exists operation
n Syntax:
collection->exists(elem : T | expr)
collection->exists(elem | expr)
collection->exists(expr)

n The exists operation results in


true if there is at least one
element in the collection for
which the expression expr is
true.
Example: exists operation
context Airport inv:
f1
self.departingFlights->exists(departTime.hour<6)
depart = 7
airp1
f2
airline1
depart = 5

f3
depart = 8 airline2

f4
airp2
depart = 9
airline3
f5
depart = 8

departing flights arriving flights


Other collection operations
n isEmpty: true if collection has no elements
n notEmpty: true if collection has at least one
element
n size: number of elements in collection
n count(elem): number of occurences of elem in
collection
n includes(elem): true if elem is in collection
n excludes(elem): true if elem is not in collection
n includesAll(coll): true if all elements of coll are in
collection
Advanced OCL Concepts
n What are constraints
n Core OCL Concepts
n Advanced OCL Concepts
n Wrap up
Result in postcondition
n Example pre and postcondition

context Airline::servedAirports() : Set(Airport)


pre : -- none
post: result = flights.destination->asSet
Statechart: referring to states
n The operation oclInState returns true if the
object is in the specified state.
Bottle
filled : enum {empty, half, full}

open closed

context Bottle inv:


self.oclInState(closed) implies filled = #full
Local variables
n The let construct defines variables local to one
constraint:
Let var : Type = <expression1> in <expression2>

n Example:
context Airport inv:
Let supportedAirlines : Set (Airline) =
self.arrivingFlights -> collect(airLine) in (supportedAirlines -
>notEmpty) and
(supportedAirlines ->size < 500)
Iterate
n The iterate operation for collections is the
most generic and complex building block.

collection->iterate(elem : Type;
answer : Type = <value> |
<expression-with-elem-and-answer>)
Iterate example
n Example iterate:
context Airline inv:
flights->select(maxNrPassengers > 150)->notEmpty
n Is identical to:
context Airline inv:
flights->iterate (f : Flight;
answer : Set(Flight) = Set{ } |
if f.maxNrPassengers > 150 then
answer->including(f)
else
answer endif )->notEmpty
Inheritance of constraints
n Guiding principle Liskov’s Substitution
Principle (LSP):
¨ “Whenever an instance of a class is expected,
one can always substitute an instance of any
of its subclasses.”
Inheritance of constraints
n Consequences of LSP for invariants:
¨ An invariant is always inherited by each
subclass.
¨ Subclasses may strengthen the invariant.

n Consequences of LSP for preconditions


and postconditions:
¨A precondition may be weakened
(contravariance)
¨ A postcondition may be strengthened
(covariance)
Wrap Up
n What are constraints
n Core OCL Concepts
n Advanced OCL Concepts
n Wrap up
Current Developments
n Feedback from several OCL
implementers handled in UML-RTF
¨ e.g. the grammar has some loose ends
¨ typical tool-related issues

n Development of OCL metamodel


¨ currently concrete syntax only
¨ will result in abstract syntax

n UML 2.0 RFP


¨ meta-model as part of the UML meta-model
¨ additional capabilities (e.g., business rules)
OCL Tools
n Cybernetics
¨ ww.cybernetic.org
n University of Dresden
¨ www-st.inf.tu-dresden.de/ocl/
n Boldsoft
¨ www.boldsoft.com
n ICON computing
¨ www.iconcomp.com
n Royal Dutch Navy
n Others … …
Conclusions and Tips
n OCL invariants allow you to
¨ model more precisely
¨ remain implementation independent

n OCL pre- and postconditions allow you to


¨ specify contracts (design by contract)
¨ specify interfaces of components more precisely

n OCL usage tips


¨ keep constraints simple
¨ always combine natural language with OCL
¨ use a tool to check your OCL
Further Resources for OCL
n The Object Constraint Language
¨ ISBN 0-201-37940-6
n OCL home page
¨ www.klasse.nl/ocl/index.htm
References
n [UML 1.3] OMG UML Specification v. 1.3,
OMG doc# ad/06-08-99
n [UML 1.4] OMG UML Specification v. 1.4,
UML Revision Task Force recommended final
draft, OMG doc# ad/01-02-13.
Further Info
n Web:
¨ UML 1.4 RTF: www.celigent.com/omg/umlrtf
¨ OMG UML Tutorials: www.celigent.com/omg/umlrtf/tutorials.htm
¨ UML 2.0 Working Group:
www.celigent.com/omg/adptf/wgs/uml2wg.htm
¨ OMG UML Resources: www.omg.org/uml/

n Conferences & workshops


¨ UML World 2001, New York, June 11-14, 2001
¨ UML 2001, Toronto, Canada, Oct. 1-5, 2001
¨ OMG UML Workshop 2001, San Francisco, Dec. 3-6, 2001

Anda mungkin juga menyukai