So#ware Architecture Bertrand Meyer, Michela Pedroni ETH Zurich, - - PowerPoint PPT Presentation

so ware architecture
SMART_READER_LITE
LIVE PREVIEW

So#ware Architecture Bertrand Meyer, Michela Pedroni ETH Zurich, - - PowerPoint PPT Presentation

Chair of Software Engineering So#ware Architecture Bertrand Meyer, Michela Pedroni ETH Zurich, FebruaryMay 2010 Lecture 12: Modeling with UML Based on slides prepared by Peter Mller, Bernd Schoeller, Nadia Polikarpova What is modeling?


slide-1
SLIDE 1

Chair of Software Engineering

So#ware Architecture

Bertrand Meyer, Michela Pedroni ETH Zurich, February‐May 2010 Lecture 12: Modeling with UML

Based on slides prepared by Peter Müller, Bernd Schoeller, Nadia Polikarpova

slide-2
SLIDE 2

2

What is modeling?

Building an abstraction of reality

  • Abstractions from things, people, and processes
  • Relationships between these abstractions

Abstractions are simplifications

  • They ignore irrelevant details
  • They represent only the relevant details
  • What is relevant or irrelevant depends on the

purpose of the model Draw complicated conclusions in the reality with simple steps in the model

slide-3
SLIDE 3

3

Example 1: cat

slide-4
SLIDE 4

4

Example 2: street map

slide-5
SLIDE 5

5

Architecture vs. Software Engineering

Problem Design Implementation Problem Model Program Reverse engineering

slide-6
SLIDE 6

6

Why model software?

Software is getting increasingly more complex

  • Windows 2000: ~40 millions lines of code
  • A single programmer cannot manage this amount of

code in its entirety Code is not easily understandable by developers who did not write it We need simpler representations for complex systems Modeling is a means for dealing with complexity

slide-7
SLIDE 7

7

What is a good model?

Intuitively: A model is good if relationships, which are valid in reality R, are also valid in model M Definition Interpretation I: R → M In a good model this diagram is commutative M M R R I fM I fR

I: Mapping of real things in reality R to abstractions in model M fM: Relationship between abstractions in M fR: Relationship between real things in R

slide-8
SLIDE 8

8

Models of models of models …

Software development is transformation of models M M R R fM

I: Requirements Elicitation

fR M2 M2 M1 M1 fM2

I2: System Design

fM1

I1: Analysis Functional Model Object Model Subsystem Decomposition

slide-9
SLIDE 9

9

Modeling the Real World

Problem domain Model

  • f problem

Representation

  • f model
  • Continents
  • Countries
  • Oceans
  • Their positions
slide-10
SLIDE 10

10

Client

possesses

Account

Balance Account No. 1 n Address Asset class

Modeling example: data modeling

Tuple of

  • Address
  • Asset class
  • At least
  • ne account

Abstraction

Bank
client
 ER-Diagram


slide-11
SLIDE 11

11

Client 1 Asset class Address Account Balance Account No. 1 1 1..*

Modeling example: object modeling

Object with

  • Data
  • Operations

Abstraction

Bank
client
 UML
Class
Diagram


slide-12
SLIDE 12

12

The Unified Modeling Language, UML

  • Modeling language = language for

describing models (mostly models of software)

  • Model in UML = graph
  • vertices = entities
  • edges = relations
  • Models can be represented in different

formats (e.g. graphical, xmi)

  • Diagrams are graphical representation of

parts of a model

slide-13
SLIDE 13

13

The Unified Modeling Language, UML

Authors: The Three Amigos Importance

  • Recommended OMG (Object Management Group)

standard notation

  • De facto standard in industrial software

development Grady Booch James Rumbaugh Ivar Jacobson

slide-14
SLIDE 14

14

A bit of history (or why “unified”?)

slide-15
SLIDE 15

15

Uses of UML

  • Specification: the language is supposed to be

simple enough to be understood by the clients

  • Visualization: models can be represented

graphically plain text < text with pictures < comics

  • Design: the language is supposed to be precise

enough to make code generation possible

  • Documentation: the language is supposed to be

widespread enough to make your models understandable by other developers

slide-16
SLIDE 16

16

What UML is not about?

  • Programming language
  • this would bound the language to a specific

computing architecture

  • however code generation is encouraged
  • Software development process
  • however the authors had their own process in

mind: RUP (Rational Unified Process)

  • CASE tool specification
  • however tools do exist: Sun, IBM Rose,

Microsoft Visio, Borland Together e.t.c

slide-17
SLIDE 17

17

Notation changes in UML 2.0

  • One notation for all structural entities - rectangle

with a stereotype:

  • Special notation for provided and required

interfaces:

slide-18
SLIDE 18

18

Canonical diagrams in UML 2.0

  • Functional
  • Use case diagram (requirements, client’s point of view)
  • Static structure
  • Class diagram (classes and relationship between them)
  • Object diagram (relationship between objects at an

interesting point in runtime)

  • Composite structure diagram (internal structure of a

class)

  • Package diagram (packages and relationship between

them)

  • Implementation diagrams
  • Component diagram (physical components and

relationship between them)

  • Deployment diagram (assigning components to nodes)
slide-19
SLIDE 19

19

Canonical diagrams in UML 2.0

  • Behavioral
  • State diagram (object lifecycle)
  • Activity diagram (= flowchart, algorithm

description)

  • Interaction diagrams
  • Sequence diagram (message passing, ordered in

time)

  • Communication diagram (message passing)
  • Interaction overview diagram (= activity diagram

with interaction diagrams in nodes)

  • Timing diagram (focus on timing constraints)
slide-20
SLIDE 20

20

The three views

  • Functional: What does the system do?
  • Interaction between the system and external

entities

  • Diagrams: use case
  • Structural: What does the system consist of?
  • Parts (modules) of the system and relationship

between them

  • Static (no notion of time)
  • Diagrams: class, component, deployment
  • Behavioral: How does the system work?
  • Notion of time or sequence of events/actions
  • Diagrams: state, activity, sequence, communication
slide-21
SLIDE 21

21

Dominance of models

Object model

  • The system has classes with nontrivial states and

many relationships between the classes Dynamic model

  • The model has many different types of events:

input, output, exceptions, errors, etc. Functional model

  • The model performs complicated transformations

(e.g., computations consisting of many steps)

slide-22
SLIDE 22

22

Aspects covered in lecture

Functional model Use case diagram (requirements, client’s point of view) Object model Class diagram (classes and relationship between them) Dynamic model Sequence diagram (message passing, ordered in time)

State diagram (object lifecycle)

+ Object constraint language (OCL)

slide-23
SLIDE 23

23

UML use case diagrams

Withdraw Client

Actors represent roles, that is, a kind of user of the system A use case represents a sequence of interaction for a kind of task Actor is potentially involved in the task System boundaries

slide-24
SLIDE 24

24

Actors

An actor models an external entity which communicates with the system

  • Kind of user
  • External system
  • Physical environment

An actor has a unique name and an optional description

  • Client: A person in the train
  • GPS satellite: An external system

that provides the system with GPS coordinates Client

slide-25
SLIDE 25

25

Use case

A use case represents a kind of task provided by the system as an event flow A use case consists of

  • Unique name
  • Participating actors
  • Entry conditions
  • Flow of events
  • Exit conditions
  • Special requirements

Withdraw

slide-26
SLIDE 26

26

Use case example: Withdraw

Initiating actor: Client Entry condition

  • Client has opened a bank account with the bank and
  • Client has received a bank card and PIN

Exit condition

  • Client has the requested cash or
  • Client receives an explanation from the Bancomat

about why the cash could not be dispensed

slide-27
SLIDE 27

27

Use case example: Withdraw event flow

Actor steps

  • 1. Authenticate
  • 3. Client selects “Withdraw CHF”
  • 5. Client enters amount

System Steps

  • 2. Bancomat displays options
  • 4. Bancomat queries amount
  • 6. Bancomat returns bank card
  • 7. Bancomat outputs specified

amount in CHF

Anything missing?

Exceptional cases Details of authentication

slide-28
SLIDE 28

28

Reusing use cases

<<include>> stereotype to include use cases: reusing common functionality, no duplicates

Withdraw Client Load Cash Card Transfer Authenticate <<include>> <<include>> <<include>>

slide-29
SLIDE 29

29

Separating variant behavior

<<extend>> stereotype to provide special case Normal case specifies point at which the behavior may diverge (extension point) Extending case specifies condition under which the special case applies (as entry condition)

Withdraw Client Refuse Withdrawal <<extend>> Not enough money Host <<initiates>> <<participates>>

slide-30
SLIDE 30

30

Withdraw event flow revisited

Actor steps

  • 1. Authenticate

(use case Authenticate)

  • 3. Client selects “Withdraw CHF”
  • 5. Client enters amount

System Steps

  • 2. Bancomat displays options
  • 4. Bancomat queries amount
  • 6. Bancomat returns bank card
  • 7. Bancomat outputs specified

amount in CHF (ext. point: Refuse Withdrawal) Listed as extension point Referring to included use case

slide-31
SLIDE 31

31

Use case Refuse Withdrawal

Entry Condition: Entered amount higher than money in account Exit Condition: Error message is displayed System Steps

  • 1. Bancomat displays error message

that entered amount is higher than available on account

slide-32
SLIDE 32

32

Generalization and specialization

Factor out common (but not identical) behavior Child use cases

  • Inherit behavior and meaning of the parent use case
  • Add or override some behavior

Flow of event:

  • Details in textual description of parent use case
  • Children describe only how they differ from parent

Withdraw Withdraw Euro Withdraw CHF

slide-33
SLIDE 33

33

Use case diagrams

  • Entities:
  • actors
  • use cases
  • Relations:
  • association between an

actor and a use case

  • generalization between

actors

  • generalization between

use cases

  • dependencies between

use cases

  • Comments:
  • system boundaries

Reader

List entries

Submitter

Log in OpenID Log in Search entries <<include>> Refuse Log in <<extend>>

slide-34
SLIDE 34

34

How to write a use case (summary)

Name of use case Actors

  • Description of Actors involved in use case

Entry condition

  • “This use case starts when…”

Flow of events

  • Free form, informal natural language

Exit condition

  • “This use case terminates when…”

Exceptions

  • Describe what happens if things go wrong

Special requirements

  • Nonfunctional requirements, constraints
slide-35
SLIDE 35

35

Aspects covered in lecture

Functional model Use case diagram (requirements, client’s point of view) Object model Class diagram (classes and relationship between them) Dynamic model Sequence diagram (message passing, ordered in time)

State diagram (object lifecycle)

+ Object constraint language (OCL)

slide-36
SLIDE 36

36

Noun-Verb Analysis (Abbott’s Textual Analysis)

Use cases represent an external view of the system No correlation between use cases and classes inside system Do a textual analysis of problem statement Take the flow of events and find participating objects in use cases and scenarios

  • Nouns are good candidates for classes
  • Verbs are good candidates for operations

First create Analysis Object Model During detailed design refine to implementation classes

slide-37
SLIDE 37

37

Classes

A class encapsulates state (attributes) and behavior (operations)

  • Each attribute has a type
  • Each operation has a signature

The class name is the only mandatory information

TarifSchedule zone2price : Table getZones( ) : Enumeration getPrice( Zone ) : Price Name Type Signature Operations Attributes

slide-38
SLIDE 38

38

More on classes

Valid UML class diagrams Corresponding BON diagram

  • No distinction between attributes

and operations (uniform access principle)

TarifSchedule zone2price getZones( ) getPrice( ) TarifSchedule TarifSchedule getZones getPrice NONE zone2price

slide-39
SLIDE 39

39

Associations

  • Most widely used relation on class diagrams
  • In general means that classes know about each other -

their objects can send each other messages (call

  • perations, read attributes)
  • Special cases:
  • Class A has an attribute of type B
  • Class A creates instances of B
  • Class A receives a message with argument of type B
  • Mostly are binary, but can be N-ary
  • Can have different adornments that express additional

information

Person Company works for Optional label employee employer Optional roles Optional roles

slide-40
SLIDE 40

40

Association adornments (1)

  • Name (possibly with direction)
  • Multiplicity of an end – how many objects of the class

take part in the relation

  • 1-to-1
  • 1-to-many
  • many-to-many

Person Company works for City Country 1 1 is capital of Polygon Point 3..* Person Company works for * *

slide-41
SLIDE 41

41

Association adornments (2)

  • Aggregation – part-of relation between objects
  • an object can be part of multiple objects
  • part can be created and destroyed independently of

the aggregate

  • Composition – strong aggregation
  • an object can only be part of a single object
  • exists only together with the aggregate

Curriculum Course * TicketMachine ZoneButton 3

slide-42
SLIDE 42

42

Association adornments (3)

  • Role of an end: name + interface
  • Navigability of an end – whether the objects at this end

can be accessed through this association

Position subordination * 0..1 chief: IChief subordinate: ISubordinate

Password Hashcode 1 1 Person Company *

slide-43
SLIDE 43

43

Relations in UML

  • Dependency – changing

the independent entity may influence the dependent one

  • Association – entities are

directly connected (e.g. aggregation)

  • Generalization – an entity

is a special case of another entity, they satisfy the substitution principle

  • Implementation – an

entity is an implementation

  • f another entity (e.g. a

class and an interface)

dependent independent entity1 entity2 descendant ancestor implementation interface

slide-44
SLIDE 44

44

Association adornments (4)

  • Ordering of an end – whether the objects at this end

are ordered

  • Changeability of an end – whether the set of objects at

this end can be changed after creation

  • Qualifier of an end – is an attribute that allows

retrieving one object from the set at this end

Polygon Point 3..* {ordered} {frozen, ordered} StockExchange Company 1 * tickerSymbol

tickerSymbol

lists

slide-45
SLIDE 45

45

Generalization and specialization

Generalization expresses a kind-

  • f (“is-a”) relationship

Generalization is implemented by inheritance

  • The child classes inherit

the attributes and

  • perations of the parent

class Generalization simplifies the model by eliminating redundancy

Polygon Rectangle

Superclass
 Subclass


slide-46
SLIDE 46

46

Stereotypes and conventions

UML provides stereotypes to attach extra classifications Naming conventions help to distinguish kinds of objects

(stereotypes lost during code generation)

<<Entity>> Account <<Boundary>> Terminal <<Control>> Withdrawal <<Entity>> Account <<Boundary>> Terminal_Boundary <<Control>> Withdrawal_Control

slide-47
SLIDE 47

47

UML packages

A package is a UML mechanism for organizing elements into groups

  • Usually not an application

domain concept

  • Increase readability of

UML models Decompose complex systems into subsystems

  • Each subsystem is

modeled as a package R Q P

<<import>> <<import>>

slide-48
SLIDE 48

48

Avoid ravioli models

Don’t put too many classes into the same package: 7 ± 2 (or even 5 ± 2)

Account Amount AccountId Deposit( ) Withdraw( ) GetBalance( ) Checking Account Withdraw( ) Savings Account Withdraw( ) Mortgage Account Withdraw( ) Bank Name Customer Name * *

slide-49
SLIDE 49

49

Put taxonomies on a separate diagram

Account Amount AccountId Deposit( ) Withdraw( ) GetBalance( ) Checking Account Withdraw( ) Savings Account Withdraw( ) Mortgage Account Withdraw( )

slide-50
SLIDE 50

50

Class diagrams

  • Entities:
  • classes (and

interfaces)

  • Relations:
  • association between

classes

  • generalization

between classes

  • implementation

between a class and an interface

  • dependencies

between classes

Position

  • ccupy

free request_report send_petition IChief send_petition ISubordinate report IPosition

  • ccupy

free Department Report Manager <<instantiate>> <<call>>

slide-51
SLIDE 51

51

UML 2.0: “Chupa-chups” notation

  • Entities:
  • classes (and

interfaces)

  • Relations:
  • association between

classes

  • generalization

between classes

  • implementation

between a class and an interface

  • dependencies

between classes

Position

  • ccupy

free request_report send_petition Department Report Manager <<instantiate>> IChief ISubordinate <<realize>> <<realize>> IPosition <<realize>>

slide-52
SLIDE 52

52

Aspects covered in lecture

Functional model Use case diagram (requirements, client’s point of view) Object model Class diagram (classes and relationship between them) Dynamic model Sequence diagram (message passing, ordered in time)

State diagram (object lifecycle)

+ Object constraint language (OCL)

slide-53
SLIDE 53

53

Overview

Object model describes structure of system Dynamic model describes behavior Purpose: Detect and supply operations (methods) for the

  • bject model

We look for objects that are interacting and extract their “protocol” We look for objects that have interesting behavior on their

  • wn

Sequence diagrams State diagrams

slide-54
SLIDE 54

54

Sequence diagrams

:Client :Terminal insertCard( ) insertPIN( )

Time

  • Entities:
  • objects (including

instances of actors)

  • Relations:
  • message passing
  • Sugar:
  • lifelines
  • activations
  • creations
  • destructions
  • frames

Actors and

  • bjects:

columns Lifeline: dashed line Activation s: narrow rectangles Messages: arrows

slide-55
SLIDE 55

55

Nested messages

The source of an arrow indicates the activation which sent the message An activation is as long as all nested activations

:Client :Terminal insertCard( ) :ClientData check( data )

  • k / nok

:Display displayMessage( text )

Data flow

slide-56
SLIDE 56

56

Creation and destruction

Creation is denoted by a message arrow pointing to the

  • bject

In garbage collection environments, destruction can be used to denote the end of the useful life of an object

:Terminal :Session start( ) Destruction log( ) close( ) Creation

slide-57
SLIDE 57

57

From use cases to sequence diagrams

Sequence diagrams are derived from flows of events of use cases An event always has a sender and a receiver

  • Find the objects for each event

Relation to object identification

  • Objects/classes have already been identified during
  • bject modeling
  • Additional objects are identified as a result of

dynamic modeling

slide-58
SLIDE 58

58

Bancomat example: Withdraw event flow

Actor steps

  • 1. Authenticate

(use case Authenticate)

  • 3. Client selects “Withdraw CHF”
  • 5. Client enters amount

System Steps

  • 2. Bancomat displays options
  • 4. Bancomat queries amount
  • 6. Bancomat returns bank card
  • 7. Bancomat outputs specified

amount in CHF (ext. point: Refuse Withdrawal)

slide-59
SLIDE 59

59

<<Entity>> :Account :Client <<Boundary>> :Terminal select ( wthdrCHF ) <<Control>> :Withdrawal initWthdr ( cur ) <<Boundary>> :Display queryAmount( ) select ( option ) wthdr ( amount ) withdraw( amount, cur ) displayConfimation( ) ejectCard( ) taken check( amount, cur )

  • kay

dispense( amount, cur )

slide-60
SLIDE 60

60

<<Entity>> :Account <<Boundary>> :Terminal select ( wthdrCHF ) <<Control>> :Withdrawal initWthdr ( cur ) <<Boundary>> :Display queryAmount( ) select ( option ) wthdr ( amount ) withdraw( amount, cur ) displayConfimation( ) ejectCard( ) taken check( amount, cur )

  • kay

dispense( amount, cur )

This
diagram
shows
only
the
successful
case
 Exceptional
case
(Refuse
Withdrawal)
could
go
either
on
another
 diagram
or
could
be
incorporated
to
this
one
 Sequence
diagrams
show
main
scenario
and
“interesting”
cases


  • interesting:
exceptional
or
important
variant
behavior


Need
not
draw
diagram
for
every
possible
case


  • would
lead
to
too
many
diagrams


:Client

slide-61
SLIDE 61

61

Interaction frames

:Item :Container :Processor process() increase()

loop [for each item]

decrease()

alt [value < 100] [else]

slide-62
SLIDE 62

62

Recommended layout of sequence diagrams

<<Entity>> :Account :Client <<Boundary>> :Terminal <<Control>> :Withdrawal <<Boundary>> :Display 1st column: Actor who initiated the use case 3rd column: Control

  • bject that manages

the rest of the use case 2nd column: Boundary object

slide-63
SLIDE 63

63

Fork structure

The dynamic behavior is placed in a single object, usually a control object It knows all the other objects and often uses them for direct queries and commands

<<Control>>

slide-64
SLIDE 64

64

Stair structure

The dynamic behavior is distributed

  • Each object delegates some responsibility to other
  • bjects
  • Each object knows only a few of the other objects

and knows which objects can help with a specific behavior

slide-65
SLIDE 65

65

Fork or stair?

Object-oriented supporters claim that the stair structure is better

  • The more the responsibility is spread out, the

better Choose the stair (decentralized control) if

  • The operations have a strong connection
  • The operations will always be performed in the same
  • rder

Choose the fork (centralized control) if

  • The operations can change order
  • New operations are expected to be added as a

result of new requirements

slide-66
SLIDE 66

66

Interaction of the models: Modeling process

Modeling usage Modeling structure Modeling behavior Functional view Structural view Behavioral view

slide-67
SLIDE 67

67

Example: modeling the ATM

Withdraw Client Load Cash Card Transfer Authenticate <<include>> <<include>> <<include>> Refuse Withdrawal <<extend>>

  • Modeling usage: use case diagram
slide-68
SLIDE 68

68

Use case example: Withdraw

Initiating actor: Client Entry condition

  • Client has opened a bank account with the bank and
  • Client has received a bank card and PIN

Exit condition

  • Client has the requested cash or
  • Client receives an explanation from the ATM about

why the cash could not be dispensed

slide-69
SLIDE 69

69

Withdraw event flow revisited

Actor steps

  • 1. Authenticate

(use case Authenticate)

  • 3. Client selects “Withdraw CHF”
  • 5. Client enters amount

System Steps

  • 2. ATM displays options
  • 4. ATM queries amount
  • 6. ATM returns bank card
  • 7. ATM outputs specified amount in

CHF (ext. point: Refuse Withdrawal)

slide-70
SLIDE 70

70

:Account :Client :Terminal select (withdraw CHF) :Withdrawal initWithdraw (cur) :Display queryAmount( ) select (option) withdraw (amount) withdraw (amount, cur) displayConfimation( ) ejectCard( ) taken check(amount, cur)

  • kay

dispense(amount, cur)

From use cases to sequence diagrams

slide-71
SLIDE 71

71

... and further to class diagrams

  • Add a class for each object on the diagram
  • For each object that receives an event add a public
  • peration in the associated class
  • Identify additional classes (e.g. for message arguments,

messages with no receivers)

  • Problem text analysis may help (nouns may correspond to

classes, verbs – to operations)

:Account check (amount, cur) withdraw (amount, cur)

  • kay

Account check (int, Currency): boolean withdraw (int, Currency)

slide-72
SLIDE 72

72

Aspects covered in lecture

Functional model Use case diagram (requirements, client’s point of view) Object model Class diagram (classes and relationship between them) Dynamic model Sequence diagram (message passing, ordered in time)

State diagram (object lifecycle)

+ Object constraint language (OCL)

slide-73
SLIDE 73

73

State-dependent behavior

Objects with extended lifespan often have state- dependent behavior

  • Typical for control objects
  • Less often for entity objects
  • Almost never for boundary objects

Examples

  • Withdrawal: has state-dependent behavior
  • Account : has state-dependent behavior (e.g., locked)
  • Display : does not have state-dependent behavior

State-dependent behavior is modeled only if necessary

slide-74
SLIDE 74

74

Events, actions, and activities

Event: Something that happens at a point in time

  • Typical event: Receipt of a message
  • Other events: Change event for a condition, time

event Action: Operation in response to an event

  • Example: Object performs a computation upon

receipt of a message Activity: Operation performed as long as object is in some state

  • Example: Object performs a computation without

external trigger

slide-75
SLIDE 75

75

State diagrams

  • Entities:
  • states: name, activity, entry/exit action
  • Relations:
  • transitions between states: event, condition, action

State 1

do / activity entry / action exit / action

State 2

do / activity entry / action exit / action event (arg) [ condition ] / action

States: rounded rectangles Transitions: arrows Start marker End marker

slide-76
SLIDE 76

76

State diagrams: example 1

On loan

entry / book.borrow( )

On shelf

entry / book.return( )

return( ) borrow( ) Copy 1..* Book borrow return borrow return

Not borrowable Borrowable

return( ) borrow( ) [ last copy ] return( ) borrow( ) [ not last copy ]

Copy Book

slide-77
SLIDE 77

77

Example 2: ticket vending machine

Idle entry/clearbalance TicketSelected entry / compute change selectTicket( tkt ) OverPaid do / dispense change [ change > 0 ] ExactlyPaid do / dispense ticket [ change = 0 ] CollectMoney [ change < 0 ] insCoin( amount ) / add to balance [ change dispensed ] [ ticket dispensed ]

slide-78
SLIDE 78

78

State

An abstraction of the attribute values of an object A state is an equivalence class of all those attribute values and links that do not need to be distinguished as far as the control structure of the class or the system is concerned Example: State of a book

  • A book is either borrowable or not
  • Omissions: bibliographic data
  • All borrowable books are in the same equivalence

class, independent of their author, title, etc.

slide-79
SLIDE 79

79

Composite/nested state diagrams

Activities in states can be composite items that denote

  • ther state diagrams

Sets of substates in a nested state diagram can be denoted with a superstate

  • Avoid spaghetti models
  • Reduce the number of lines in a state diagram
slide-80
SLIDE 80

80

State diagrams: example composite state

Off On Working Blinking Red Yellow Yellow Green Red Green TurnOn TurnOff SwitchOn SwitchOff after 3 sec after 45 sec after 5 sec after 30 sec

TrafficLight

slide-81
SLIDE 81

81

Example: superstate

Idle entry / clear balance CollectMoney TicketSelected entry / compute change ExactlyPaid do / dispense ticket OverPaid do / dispense change insCoin( amount ) / add to balance selectTicket( tkt ) [ change > 0 ] [ change = 0 ] [ change < 0 ] [ change dispensed ] [ ticket dispensed ]

Superstate

slide-82
SLIDE 82

82

Expanding the superstate

Transitions from other states to the superstate enter the first substate of the superstate Transitions to other states from a superstate are inherited by all the substates (state inheritance)

do / store coins do / issue ticket do / print ticket ExactlyPaid do / dispense ticket [ change = 0 ] [ change dispensed ] [ ticket dispensed ]

Dispense as atomic activity Dispense as composite activity

slide-83
SLIDE 83

83

State diagram vs. sequence diagram

State diagrams help to identify

  • Changes to an individual object over time

Sequence diagrams help to identify

  • The temporal relationship between objects
  • Sequence of operations as a response to one or more

events

slide-84
SLIDE 84

84

Practical tips

  • Create component and deployment diagrams only for

large, distributed systems

  • Create state diagrams only for classes with complex,

interesting behavior (usually classes representing entities from the problem domain or performing control)

  • Create activity diagrams for complex algorithms and

business processes (not for every operation)

  • Create sequence and communication diagrams for

nontrivial collaborations and protocols (not for every scenario)

  • Don’t put too much information on a diagram
  • Choose the level of abstraction and maintain it
slide-85
SLIDE 85

85

Entities in UML

  • Structural
  • Class – a description of a set of object

with common attributes and operations

  • Interface – a set of operations (a service),

provided by a class or component

  • Actor – an external entity that interacts

with the system

  • Use case – a description of a set of

scenarios (sequences of events and actions) that produce a result, significant for some actor

  • Component – physically replaceable

artifact that provides a certain set of interfaces

  • Node – a hardware resource
slide-86
SLIDE 86

86

Entities in UML

  • Behavioral
  • State – a period in an object lifecycle,

during which the object is satisfying some property, performing an activity

  • r waiting for an event
  • Activity – a state, in which the object

is doing some work (instead of just passively waiting for an event)

  • Grouping
  • Package – a group of model elements

(maybe including other packages)

  • Annotating
  • Note – arbitrary text comment

attached to a model

slide-87
SLIDE 87

87

Relations in UML

  • Dependency – changing

the independent entity may influence the dependent one

  • Association – entities are

directly connected (e.g. aggregation)

  • Generalization – an entity

is a special case of another entity, they satisfy the substitution principle

  • Implementation – an

entity is an implementation

  • f another entity (e.g. a

class and an interface)

dependent independent entity1 entity2 descendant ancestor implementation interface

slide-88
SLIDE 88

88

Aspects covered in lecture

Functional model Use case diagram (requirements, client’s point of view) Object model Class diagram (classes and relationship between them) Dynamic model Sequence diagram (message passing, ordered in time)

State diagram (object lifecycle)

+ Object constraint language (OCL)

slide-89
SLIDE 89

89

UML is not Enough

Urs is married to Sile, Sile is married to Beat, and Beat is not married at all A valid instantiation of the class diagram! Associations describe relations between classes

Person Marry( ) spouse 0..1 Urs: Person Sile: Person Beat: Person spouse spouse “is married to”

slide-90
SLIDE 90

90

UML is not Enough (cont’d)

Urs is married to Sile, who is only eleven A valid instantiation of the class diagram! Class diagrams do not restrict values of attributes

Person age spouse 0..1 Married persons are at least 16 years old Sile: Person spouse spouse age = 11 Urs: Person age = 18

slide-91
SLIDE 91

91

Expressing Contracts

Natural language

  • Advantage: Easy to

understand and use

  • Disadvantage:

Ambiguous Mathematical notation

  • Advantage: Precise
  • Disadvantage: Difficult

for normal customers Contract language

  • Formal, but easy to use
  • Examples: Eiffel, JML

spouse expresses “is married to” spouse /= Void implies spouse /= Current and spouse.spouse = Current spouse: Person → Person spouse = spouse–1 spouse ∩ id = ∅ ∀p: Person: p ∈ dom( spouse ) ⇒ spouse( p ) ∈ dom( spouse ) ∧ p ≠ spouse( p ) ∧ p = spouse( spouse( p ) )

slide-92
SLIDE 92

92

Object Constraint Language – OCL

The contract language for UML Used to specify

  • Invariants of objects
  • Pre- and postconditions of operations
  • Guards (for instance, in state diagrams)

Special support for

  • Navigation through UML class diagram
  • Associations with multiplicities
slide-93
SLIDE 93

93

Form of OCL Invariants

Constraints can mention

  • self: the contextual

instance

  • Attribute and role

names

  • Side-effect free

methods (stereotype <<query>>)

  • Logical connectives
  • Operations on integers,

reals, strings, sets, bags, sequences

  • Etc.

context Person inv: self.age >= 0

The context is an instance of a class in the UML diagram Declares an invariant A boolean constraint

slide-94
SLIDE 94

94

OCL Invariants: Example

A savings account has a non- negative balance Checking accounts are

  • wned by adults

context SavingsAccount inv: self.amount >= 0

Account amount CheckingAccount SavingsAccount Customer age *

  • wner

context CheckingAccount inv: self.owner.age >= 18

Role name

slide-95
SLIDE 95

95

OCL Invariants: Contexts

Checking accounts are

  • wned by adults

Accounts are owned by adults Customers are adults context CheckingAccount inv: self.owner.age >= 18 context Account inv: self.owner.age >= 18 context Customer inv: self.age >= 18

Account amount CheckingAccount SavingsAccount Customer age *

  • wner
slide-96
SLIDE 96

96

forAll( expression ) isEmpty( ) exists( expression ) size( ) includes( object )

Collections

OCL
provides
three
predefined
collection
types


  • Set,
Sequence,
Bag


Common
operations
on
collections


True iff expression is true for all elements True iff collection contains no elements True iff expression is true for at least one element Number of elements in the collection True iff the object is an element

slide-97
SLIDE 97

97

Generating Collections

Explicitly enumerating the elements By navigating along 1:n associations

  • Navigation along a single 1:n

association yields a Set

  • Navigation along a single 1:n

association labeled with the constraint { ordered } yields a Sequence

Account amount Customer age * accounts { ordered }

Set { 1, 7, 16 } self.accounts

slide-98
SLIDE 98

98

Example: Multiplicity Zero or One

Person age spouse 0..1

context Person inv: spouse->size( ) = 1 implies age >= 16 and spouse.spouse = self and spouse <> self

self can be

  • mitted

spouse used as set spouse used as object

slide-99
SLIDE 99

99

Example: Quantification and Type Information

Account amount CheckingAccount SavingsAccount Customer age *

  • wner

accounts

context Customer inv: age <= 18 implies accounts->forAll( a | a.oclIsKindOf( SavingsAccount ) )

Subtype relation ∀a∈accounts: a.oclIsKindOf( Savingsaccount )

slide-100
SLIDE 100

100

Example: Composite Pattern

A composite is the parent of its components A component is contained in its parent composite

Leaf Composite * Component children parent 0..1

context Composite inv: children->forAll( c | c.parent = self ) context Component inv: parent->size( ) = 1 implies parent.children->includes( self )

slide-101
SLIDE 101

101

Contracts in Eiffel: Method Specifications

Method precondition

  • Must be true before the method is executed

Method postcondition

  • Must be true after the method terminates
  • old expressions is used to refer to values of the

pre-state

class interface ACCOUNT feature withdraw ( a: INTEGER ) is require a >= 0 ensure GetBalance( ) = old( GetBalance( ) – a ) end

slide-102
SLIDE 102

102

Pre- and Postconditions in OCL

result is used to refer to return value Pre- and postconditions can be named (like in Eiffel) context Account::Withdraw( a: int ) pre: a >= 0 post: GetBalance( ) = GetBalance@pre( ) - a

Context specifies method signature Suffix @pre is used to refer to prestate values

slide-103
SLIDE 103

103

Alternative Notation

Contracts can be depicted as notes in diagrams

  • Stereotypes instead of keywords inv, pre, post

Account Amount: int AccountId: int Deposit( a: int ) Withdraw( a: int ) GetBalance( ): int <<precondition>> a >= 0 <<invariant>> AccountId >= 0 <<postcondition>> GetBalance( ) = GetBalance@pre( ) - a