Você está na página 1de 55

PROJECTING OF

INFORMATION SYSTEMS

Aim of the course:


• Object oriented approach to building systems
• Principles and techniques of an object modelling
• UML methodology as an instrument for analysis
and design
Literature:
• Michael Blaha a James Rumbaugh: Object-
oriented modelling and design with UML.
Prentice-Hall. 2005.
• James Martin, James J. Odell: Object oriented
methods. Prentice-Hall, 1995.
• Ivan Vrana, Karel Richta: Zásady a postupy při
zavádění podnikových informačních systémů.
Grada, 2004.
Pass conditions:
Class credit: test - 5 points minimum, project,
max. 2 un-excused absence.
Exam: Project defence
Knowledge in the scope of lectures, at least.

2
What is object oriented

• Organising SW as a set of separate objects with a


data structure and behaviour
• New way of thinking about problems
• Object – a basic building element
• It combines a data and a functional perspectives
• Basic characteristics of an object:
a) identity
b) classification
c) polymorphism
d) inheritance

a) Identity:
• Identity means that data are separated into
distinguishable entities – objects
• Each object has its own identity
(2 objects might be different in spite of
identical values of all attributes (name, size,...)
• Objects might be concrete as well as abstract
Examples:

Father’s case Mother’s case Cow Anchor

3
Variable name address
Credit 20030056
Debt 12365478
Account 96385274
table

b) Classification:

• Objects with the same data structure (attributes)


and same behaviour (operations) are grouped
into class.

• Class describes important features for an


application and ignores the rest.

• Class is (infinite?) set of individual objects.

• Each individual object is an instance of his class.

• Each class instance has its own values of all


attributs, but it shares a common structure
(names) of attributes and operations with other
instances of the same class.

4
Case Objects Case Class

Attributes
height
width
Abstract into depth
color

Operace
store
fill
repair

Cup Objects Cup Class


Attributes
content
purpose
material

Abstract into
Operations
fill
empty
clean

5
c) Polymorphism
• The same operation can behave differently in
different classes
E.g. the MOVE operation is different for a horse
and rook in the chess game.
• A specific implementation of operation at a
certain class is called a method.
• An operation can be implemented by more than
one method (because of polymorphism).

d) Inheritance
• Sharing of attributes and operations among
classes at a hierarchical principle.
• A superclass contains general information that
subclasses refine.
• Every subclass inherits all features of its
superclass and adds its own unique features.
• This principle is one of basic advantages of the
OO approach which considerably reduces
repetitions in a design.
What is Object Oriented development
• Essence of the OO approach is to distinguish and
to order application domain concepts (and not a
final expression by a programme).
• Model is a tool to understand and describe
reality.

6
Life-cycle phases of the OO metodology:
1. System conception
• System development begins with a problem
formulation.
2. Analysis
• Rising from a problem formulation – building a
real world model (significant features).
• Model is a concise precise abstraction of what
the desired system must do (not how it will be
done).
• It should not contain implementation decisions.
• Analysis model has two parts:
- Domain model (real world objects)
- Application model (visible to the user).
2. System design
• An overall architecture and its principles.
• Decomposition into subsystems.

3. Class design
• Adds (implementation) details to analysis models
• The focus is the data structures and algorithms of
individual object classes.
4. Implementation
• Object classes and their relationships are
converted to a programming language, database
and hardware implementation.
7
Three models
1. Class model
• Static structure of objects and their relationships.

• Class diagram: objects=nodes,


relationships =edges.
2. State model
• Changes of system aspects in time.

• State diagram: states=nodes, events=edges.

3. Interaction model
• Cooperation of objects in a system.

• Diagrams: Use Case, Sequential, Activity.

⇒These 3 models supplement each other and are


cross-linked.
⇒Class model is fundamental because we should
first describe what is subject to a change before
when and how.
Supported principles
Abstraction: focus on essential aspects of an
application and neglecting details. It is a tool to
deal with complexity.
Encapsulation: Separates external aspects of
classes from implementation details.
Sharing: Inheritance of both: data structure and
behaviour enables to share a common code. A
conceptual clarity is still more important.

8
Object modeling

• Model is an abstraction of reality, in order to


understand reality first.
• Model ignores nonessential details = a way to
deal with complexity.
• Class model depicts a static structure of the
system and shows:
- objects in a system
- relationships between objects
- attributes and operations, characterizing each
object class.
• Class model is the most important of 3 models as
it provides an intuitive graphical representation
of the system.
• We shall use the UML notation.
• Important concepts: object, class, link,
association, generalization, inheritance.

9
Objects and classes
• Object is a subject of our interest in a system.
• All objects have identity and are distinguishable.
• One object = instance.
• Object class describes a group of objects with
similar features (attributes), common behaviour
(operations), same associations with other
objects
e.g.: person, factory, animal, process,....
• Objects and classes occur as nouns in a problem
description.
• Objects in a class share a common semantic
purpose (which is superior to requirement of
same attributes and behaviour)
e.g.: a barn and a horse have same attributes
age and cost – they yet can belong to different
classes.
• By grouping objects into classes we gain several
advantages. For example:
Common definitions are stored only ones for a
class instead for each instance,
Operations are described ones for a class –
possibility to reuse a code.

10
Class diagrams
• A tool for accurate and easy expression of an
object model. Two types of object diagrams in
UML:

Class diagram: (general) Person

Instance diagram: (examples to clarify)

JohnSmith: Person AnnBrown: Person : Person

Attributes
• Attributes describe data features of an object
• Attributes are introduced in the second part of a
class icon, separated from a class name by a
horizontal line.

Person AnnBrown: Person JohnSmith:Person


name: string name=”Ann Brown” name=”John Smith”
age : integer MMMalá”
age= 43 řetězec MMMalá”
age= 25 řetězec

Class with Objects with values


attributes
• Each attribute name can be followed by optional
details as a type and a default value.
• The type is separated by a colon, default value
by an equality sign.

11
• A class model doesn’t require explicit object
identifiers (each object is implicitly identified by
its own identity).
• Don’t confuse internal (programming) identifiers
with real attributes.

Person
personID_: ID
name: string
age: integer

Wrong!

Operations and Methods


• Operation is a function or transformation, which
is performed by or at an object in the class.
Example:
PRINT operation holds for a FILE class,
MOVE, SELECT, ROTATE operations hold for
a POLYGON class.
• All objects in a class share same operations.
• Each operation has a target object as an implicit
argument.
• Operation can have further arguments (in
addition to a target object).
• A method is an implementation of an operation
at a class.

12
• As a consequence of polymorphism, same
operation can hold for a number of various
classes where it can have various forms.
E.g. PRINT operation for classes FILE binary or
ASCII.

• If operation has methods at several classes, then


all these methods have the same signature, i.e.
number and type of arguments and a result type.

• Common name for attributes a operations is


feature.
• Operations are shown in the lower (third) part of
a class icon.

Person File Polygon


name fileName color
age lastAccess position
addressChange sizeInBytes rotate(angle)
jobChange print move (delta: Vector)
select (p: Point): Boolean

• Each operation name can be supplemented by a


list of arguments and a result type.
• List of arguments is shown in brackets after a
name, arguments are separated by commas.
• An empty list of arguments between brackets
explicitly shows that operation has no arguments.
• A result type is preceded by a colon.

13
Summary of the object class notation

ClassName
atr1: data type 1 = init.value 1
atr2: data type_2 = init.value 2
oper1 (list of_arguments 1): result1
oper2 (list of_arguments 2): result2

Links and Associations

• Link is a physical or conceptual relationship


between object instances.
E.g.: John Smith works at UNO
• Link shows relationship among two or more
objects (mathematically it is an n-tuple: list of
objects).
• Link is occurrence of an association.
• Association describes a group of links with the
same structure and semantics (sense).
• Link and association often occur as a verb in a
problem description.
• Association is bi-directional by its nature.

14
• Each association in a class diagram corresponds
to a set of links in an instance diagram similarly
as an object class corresponds to a set of objects.
• UML notation pro association and link is a line
connecting classes or instances.
• Association and link names are typed in italics.
Link name is underlined.
• The name can be omitted if it is single and clear.
Example:
HasCapital
Country City
name name

Class diagram

HasCapital
Italy:Country Rome:City
name=”Italy” name=”Rome”

HasCapital
France:Country Paris:City
name=”France” name=”Paris”

HasCapital
Russia:Country Moscow:City
name=”Russia” name=”Moscow”

Instance diagrams

15
Cardinality and Multiplicity
• Multiplicity specifies how many instances of one
class may relate to a single instance of an
associated class.
• Multiplicity constrains the number of related
objects. Cardinality is a number of elements that
are actually in a collection.
• In UML multiplicity is indicated by a symbol at
the ends of association lines.
Symbols: Meaning:
1:
1 IsMarriedWith 0..1
Man Wife
0 or 1

Director 1 Manages School


1

StraightLine 1 Crosses * Point


0 or many

1 Has 1..*
Book Copy
1 or many
vícvíce
1 Contains 8..20
Group Student
8 to 20

• In early stages we first determine objects,


classes, associations and only later we deal with
multiplicity.

E.g.: Has an association between objects Person


and Company multiplicity 1:N or N:N?

16
Association classes
• An association class is simultaneously an
association and also a class.
• Attributes can describe feature of an association
similarly as they describe features of a class.
* *
F ile User

A c c e s s ib le F o r
a c c e s s R ig h t

/etc/termcap (read) John Brown


/etc/termcap (read-write) Ann Green
/usr/brown/.login (read-write) John Brown
• Association attributes are justified mainly in
many-many associations.
• Such an attribute is undoubtedly a feature of a
link and cannot be assigned to any object.
• It could be used also for 1:many associations.

• It is possible to place attributes into the object at


the “1” side of the 1:many association. Not
recommended.
* 0..1
Person W orksFor Com pan y
nam e nam e
birthD ate
address
changeO fAddress
changeO fJob salary

0..1 M anages *
boss em plyee

qualification

17
* *
User WorkStation

Authorisation
e
priority
accessRights

startingWorks

* homeFolder
0..1

Folder

Role names
• Role is one end of an association.
• Binary association has two roles each of them
can have a name.
• A role name uniquely identifies one end of an
association. Role names are usually nouns.
• Role names can substitute or supplement
association names.
• Role names are compulsory for an association of
two objects of the same class (see example
PERSON).

18
Person WorksFor Company
name
birthDate address
name
changeAddress employee employer
changeJob

John Smith CULS


Ann Brown CULS
Jack Smile CTU

• Role names are useful to distinguish two


associations the same pair of classes.

* Owner 0..1 content


User Folder
hasRights *
0..1

container

• A role name is a pseudo attribute of the


corresponding class and, therefore, it should be
unique (and different than real real attributes).
Ordering
• Objects at the “many” side of an association
usually don’t have an explicit ordering (can be
considered a set).
• But sometimes object have an explicit ordering.
E.g. a PC screen contains several overlapping
windows, but only the top-most one is visible.

19
{ordered}
PCscreen Window
1 VisibleAt *

• Ordering is a feature of an association and is


indicated by {ordered} near the relevant
association end.
Bags and sequences
• An ordinary association has at most one link for
each pair of objects.
• Sometimes we can allow multiple links for a pair
of objects by annotating {bag} or {sequence} the
corresponding association end.
• Bag is a collection of elements with duplicates
allowed.
• Sequence is an ordered collection of elements
with duplicates allowed.
• E.g.: An itinerary is a sequence of airports while
the same airport can be visited more than once.

{sequence}
Itinerary Airport
* *

• {ordered} and {sequence} denote the same thing


with a difference that {ordered} disallows and
{sequence} allows duplicates of elements.

20
Qualification
• Qualified association puts to relationship two
object classes and a qualifier.
• Qualifier is a special attribute which effectively
reduces multiplicity of an association.
• We can qualify 1:many and many:many
associations.
1 *
Folder File

• Qualificator distinguishes objects at the “many”


end of association.
• Qualification reduces multiplicity of this
association from 1:many at 1:1.

1 0..1
Folder FileName File

• Qualifier is drawn as a small box at that side of


association, which it qualifies.
E.g.: Folder+FileName determine File
⇒ therefore a small box is next to Folder.
• Qualification improves semantic accuracy and
clarity of an association.

21
Aggregation
• Aggregation is a special type of association, not
a new concept.
• Aggregation is an object relationship of a type
“part-assembly”.
• Symbol of aggregation is an association line with
a “diamond” at a side of assembly.
• Aggregation can have arbitrary number of levels.
Microcomputer

1..* 1 1 1

Monitor Case Keyboard Mouse

Chassis Processor RAM Fan

• Aggregation can be of a type “is composed


from” or “is a part of”.
• Aggregation is transitive and antisymetric.
• Features propagate from assembly to parts and
not conversely.
- E.g.: print

Book * Chapter * Sentence

22
Composition
• A special case of aggregation for which two
limitations hold:
- Part can belong to only one assembly
- Part disappears by disappearing of assembly
• A solid diamond is a graphical symbol of a
composition

Company 1 * Factory 1 * Workshop

Generalisation and inheritance


• Powerful way to share similarity between classes
while preserving their differences.
• Generalisation is a relationship between a
superclass and its special cases subclasses.
E.g. Equipment is a superclass for Tank, Pump,….
• Each subclass inherits features of its superclass
(attributes, operation, associations).
• Generalisation and inheritance are transitive
across arbitrary number of levels.
• The terms Ancestor and Descendant refer to
generalisation across several levels.

23
• Generaliation is the “Ia a” relationship, because
each of a subclass is also an instance of all
superclasses.
• State of instance contains attribute values of all
ancestors.
• Each subclass not only inherits all features of its
ancestors, but it also adds its own specific
attributes and operations.
E.g. Pump adds an attribute flowRate, which
other types of Equipment don’ share.
• Notation for generalisation is a small triangle
connecting a superclass with its subclasses.
• Each object inherits features from one class in
every generalisation level.
• Discriminator is an optional name indicating
which aspect of the system is abstracted by a
particular generalisation. It is placed next to the
small triangle icon.
• Only one aspect can be abstracted in at a time.
E.g. a Vehicle class can be abstracted according
to a type of engine or operational environment..
• It is not suitable to organize generalisation to
excessive many levels, it is confusing.
2-3 levels is OK, 5 is already too much.

24
Equipment
cost
name
weigth
producer

EquipmentType

Pump Exchanger Tank


suctionPresure length volume
flowRate surface presure
diameter

PumpType

Centrifugal PistonPump MembranPump


revolutions stroke surface
bladeNumber
TankType

SphericTank PresureTank OpenTank


diameter diameter diameter
height height

PistonPump:Pump Exchanger:Equipment PresureTank:Tank

cost = 9000 CZK cost = 7500 CZK cost = 6200 CZK


name = “KOMP” name = “STABIL” name = “TANK”
weight = 3.6 kg weight = 9.3 kg weight = 15.6 kg
producer = “ČKD” producer = “ČKD” producer = “GM”
suctionPr= 2.5 atm lenght = 1.2 m volume = 1500 l
flowRate = 26 m surface = 16 m2 presure= 1.5 atm
diameter = 0.39 cm
stroke = 12 cm diameter = 1 m
height = 2 m

• Generalisation is a useful instrument for


conceptual modelling and also for
implementation.

25
Overriding rules
• A subclass can override a superclass feature by
defining a feature with the same name.
E.g.: operation ROTATE is a standard one for
displaying geometric figures. It could be a null
operation for a CIRCLE class.
• We can suppress original values of attributes and
methods of operations. But a signature, a form of
a feature, mustnot be suppressed.
• Features cannot be suppressed in a way to
become inconsistent with a signature or meaning
of originally inherited feature.
Navigation of class models
• So far we have shown how to express an
application structure.
• We can also express how to navigate among
classes.
• We can navigate manually or to navigation
expressions.
• Example:
Let us consider a simple model of credit card
accounts

26
PostAddress CreditCardAcc Institution
1 * 0..1 1
a accountN n
address maxCredit name
telNumber currentBalanc address
ee telNumber
* statemDate

1
* accountOwner 0..1
Customer Statement 0..1 Transaction
1
transactionN
name dueDate transactionDate
amount purpose
minPayment amount

Cash Interest Purchase Fee

1
Merchant

name

• We can ask a variety of questions against the


model, e.g. :
- What transactions occurred for a credit card
within a time interval?
- What volume of transactions was handled by
an institution last year?
- What customers paid at a merchant by any
kind of credit card?
- How many credit card accounts does a
customer currently have?
- What is the total maximum credit for a
customer for all accounts?

27
• UML contains an OCL (Object Constraint
Language), which can express the above
questions.

OCL language (Object Constraint Language)


OCL can traverse the constructs in a class model:
• Attributes:
we can traverse from object to an attribute value
Syntax: source object dot attribute name
Convention: „a“ preceeds a class name to refer to
an object
Example: aCreditCardAcc.maxCredit

• Operation: we can invoke an operation for an


object or a collection of objects
Syntax: source object dot operation
Operace must be followed by parentheses even if it
has no arguments (to avoid confusion with
attributes)
Syntax for collection of objects:
collection of source objects -> operation.

28
• Simple association:
Syntax:
source object dot role of target object
or: target object
Ex.: aCreditCardAcc.PostAddress

• Qualified association:(for more precise traversal)


Syntax: Qualifier value is in brackets
Ex.: aCreditCardAcc.Statement[30 Jan 2008]

• Filters: for distinguishing objects in a set


The OCL has several kinds of filters – the most
common of which is the select operace. Outputs of
this operation are elements satisfying the predicate.
Ex.:
aStatement.Transaction -> select(amount>10 €)

Vytváření OCL výrazů


• Power of OCL comes from v combining
primitive constructs into expressions
Ex. OCL expression can chain together several
association traversals. There could be several
qualifiers, filters and operators.

29
• In OCL, traversal from an object through a single
association yields a singleton or a set (or a bag, if
association has an annotation {bag} or {sequence}.
• Set is a collection of elements without
dupplicates, bag is a collection of elements with
dupplicates allowed.
Example, how OCL expression yields a bag:

OwnsStock
PostAddress Person Company
address * * name * * name

:PostAddress

address=“AA“ Jim:Person

name=“Jim“
:PostAddress

address=“BB“ IBM:Company
John:Person

name=“John“ name=“IBM“
:PostAddress

address=“CC“ Ann:Person

name=“Ann“
:PostAddress

address=“DD“

30
Examples of OCL expressions
Let us use OCL to answer questions to the credit
card:
- What transactions occurred for a credit card
within a time interval?
aCreditCardAcc.Statement.Transaction ->
select(aStartDate <= transactionDate and
transactionDate <= aEndDate)
- What volume of transactions was handled by an
institution last year?
aInstitution.CreditCardAcc.Statement.Transaction
-> select(aStartDate <= transactionDate and
transactionDate <= aEndDate).amount -> sum()
- What customers paid at a merchant by any kind
of credit card?
aMerchant.Purchase ->
select(aStartDate <= transactionDate and
transactionDate <= aEndDate).Statement.
CreditCardAcc.PostAddress.Customer -> asSet()
- How many credit card accounts does a customer
currently have?
aCustomer.PostAddress.CreditCardAcc ->size()
- What is the total maximum credit for a customer
for all accounts?
aCustomer.PostAddress.CreditCardAcc.maxCredit
-> sum()

31
Metadata
• Metadata are data, which describe (define) other
data.
• Examples of metadata: class definition, general
models, catalogues of components,
dictionaries,…
Example of relationship between data a metadata:

CarModel PhysicalCar
Popisuje
modelName serialNumber
year color
1 *
basicPrice accessories
* *

1 manufactucer 1 owner

Company Person

• Model of a car has a name, year, price, … e.g. :


• Model of a car is: Ford Mustang 1969, Toyota
Corolla 2007, ...
• A physical car has a certain serial number,
color, accessories. It also has its owner.
• A car model (metadata) describes properties of
many physical cars and contains their common
data.

32
Packages
• Split large models into smaller parts –
packages, in order to improve understanding.
• A package is a group of elements (classes,
associations, generalizations and lower level
packages) with a common theme.
• Packages create a tree, where a level of
abstraction increases towards the root.
• Packages are denoted by a box with a tab.

PackageName

• Themes for forming packages can be e.g. a


dominant class, dominant association,
functionality, symmetry, etc.
• Carefully determine a package’s scope
• Each class is defined in a single package. Other
packages refer to this class by its name only.
• Make packages cohesive:
- Each association and generalization can
occur only in one package.
- Packages are binded by classes (which can
occur in several packages).

33
Practical tips
• First we should understand a problem on hand.
• Try to keep model simple.
• Carefully choose names; descriptively,
unambiguously (it is difficult).
• Do not hide pointers in object as attributes.
Instead, model them as associations.
• Do not try for perfectness in multiplicity too
early. Start with considering multiplicity of „1“.
• Beware of repeated use of the same class. Role
names can help.
• Do not collapse association attributes into a
class.
• Use qualified associations, whenewer possible.
• Avoid deeply nested generalizations.
• Don’t be surprised if our class model still needs
corrections. Let others to evaluate our model.
• Always document our class models.
• Don’t try to use all available instruments. Choose
only those which are helpful to given purpose.

34
Dynamic modeling

• System could be best understood, if we first


examine its static structure.
• Then we examine changes of objects and their
relationships = we build a dynamic model.
• The main concepts of dynamic modelling: event,
state, state diagram.
• State is a collection of attribute values and links
in a given time instant.
• In a course of time, objects mutually stimulate
each other which results in changes of their
states.
• A stimulus from one object to another one is an
event.
• Reaction of an object to an event depends from
its state.
• A state diagram is a graph of events and states,
analogically as a class diagram is a graph of
classes and their associations. A dynamic (state)
model consists from many state diagrams, one
for each class.

35
Events
• An event is something which happens in a time
instant.
Ex.: user pushed a mouse button,
arrival of flight 321 from Rome.
• An event has no duration.
• Events may logically preceed or follow other
event, or two evevnts may be independent.
Ex.: Event Landing of flight 321 from Rome must
be preceded by an event Departure of flight 321
from Rome.
Event Landing of flight 321 from Rome can occur
independently to the event Departure of flight
456 from Melbourne.
• Two events which are causally unrelated are
called concurrent. They have no effect on each
other.
• Both normal and error situations belong to events
– depending on our interepretation.
• The time at which an event occurs is its implicit
attribute.
• Events are of several types: signal events, change
events and time events.

36
Signal events
• Signal event is an explicit one-way transmission
of information from one object to another one.
• Signal event is sending or receipt of a signal (we
are usually more concerned about a receipt).
• Each signal event has a unique occurrence, but
we group them to signal classes and give them a
name (to express a common structure and
behavior).
Ex.: Flight 321 from Rome landed
Flight 765 from London landed
are instances of event class Flight landed.
• Some signal events are a simple occurrence but
majority of event classes has attributes.
Ex.: Flight landed has attributes: airlines, flight
number, city, date.
• UML notation is a keyword «signal» above the
signal class name

«signal» «signal»
FlightLanded MouseButtonPressed
airlines button
flightNumber position
city
date

37
• Attributes are shown (eligibly) in brackets
following an event class name.
Ex.: MouseButtonPressed(button, position)
FlightLanded(airlines, flightNumber, city, date)
StringEntered(text).

Change events
• Change event is caused by satisfaction of a
boolean expression – an event happens when
value of expression changes from FALSE to
TRUE.
• UML notation is a keyword when followed by a
Boolean expression in brackets
Ex.: when(room Temperature<startHeating)
when(room Temperature<startCooling)
when(bateryVoltage<lowerLimit)

Time events
• Time event is caused by reaching an absolute
time or after a time interval was expired.
• UML notation for an absolute time is a keyword
when followed by a time expression in brackets,
for interval a keyword after (length of interval)
Např.: when(date=24.12.2008)
after(10 seconds).

38
States
• State is an abstraction of attribute values and
object links.
• Values are grouped together into states according
to the gross behaviour of objects.
Ex. A bank is either solvent or insolvent.
• In defining a state we ignore attributes, which do
not affect the behaviour of the object.
• Object can have a finite number of states and it
can move through one or more states during its
lifetime.
• State defines a response of the object at input
events.
• Object in a given state reacts only at certain
events and ignores the rest.
• Events represent time instants, states represent
time intervals.
Ex.: After the receiver is lifted and before we dial
the first digit, the phone line is in state Dial tone.
• State of object depends on the previous sequence
of events. The past events are often hidden by
the next event.

39
Ex.: events, which occurred before lifting a
receiver, have no effect on a future behaviour of
a phone line (are forgotten).
• Events and states are in a dual relationship: an
event separates two states and a state separates
two events.

Power Power Power


turned on turned off turned on

time

Powered Not powered

• Both events and states depend on the used level


of abstraction (on the needed level of details –
the time granularity).
Ex.: A flight segment is an event for a travel agency
and a state for a pilot of an airplane.
• State is often characterized with the fact that a
some attribute satisfies a certain condition.
Ex.: Water is a liquid is equivalent with a
condition Water temperature is between 0 and
100 °C.

40
• State can be expressed in many different ways:
Example:
State: An alarm clock rings
Description: An alarm clock rings in order to
indicate target time
Sequence of events, leading to the state:
switch alarm on
no action containing switching alarm off
actual time=target time (AT = TT)
Conditions which characterize the state:
alarm switched on and
TT ≤ AT≤TT+20 sec. and
no button pressed after TT.
Events received in the state (table
stimuli/reactions):
Event action next state
AT = TT+20 switch alarm off normal
press any button switch alarm off normal

41
State diagrams
• State diagram (SD) shows relationship of events
and states.
• When an event occurs, next state depends on this
event and a present state.
• Change of a state caused by event is transition.
• Nodes in SD are states and oriented links
(arrows) are transitions marked by event names.
• Notation:
• State: Oval with optionally inscribed name.
• Transition: Arrow (from present to next state).
Text next to the arrow is an event name.
• Initial state: solid circle.
• Terminal state: “Bulls eye”.
• SD describes behaviour of a single object class.
• Because all objects of the same class have the
same behaviour (by definition), they all share the
same SD.
• Dynamic (state) model is a collection of state
diagrams of all objects which mutually affect
each other by means of shared events.
• Aktivation of transition leading to a change of
state is called fireing of a transition.
42
Phone line
onHook onHook
Idle
offHook

DialTone time-out
Time-out
digit digit
time-out
Dialing Message
invalid n.
busy
BusyTone valid number
Connecting

connected

Ringing

calledPhoneAnswers

Connected
callerHangsUp

messageDone
Disconnected

Example of a one-shot SD: Chess game

start checkmate
White’s turn
Black wins

white black
moves moves stalemate
Draw

Black’s turn
checkmate White wins

43
Conditions
• Condition is a Boolean function of object values.
Ex.: “temperature is below a freezing point”
• Condition holds in a time interval (in contrast to
an event, which has no duration).
Ex.: “It was freezing since Dec. 5th 2003 till
Jan. 3rd 2004”.
• Condition can serve as a guard on transitions. (It
is shown as a Boolean expression in brackets
next to the event name).
• Transition is fired only in a case, when condition
is satisfied at a moment when event occurred. It is
not fired if condition is satisfied later.
Example: Traffic lights at an intersection
time-out (cars in N/S
left lanes)
N/S straight N/S left

time-out (no cars in


N/S left lanes)

time-out time-out

time-out (no cars in


E/W left lanes)

E/W left E/W straight


time-out (cars in E/W
left lanes)

• Condition is not same as a change event (CE).


Condition is tested once whilst CE permanently.

44
Activities
• Description of object behaviour should show
what object is doing in response to an event.
• Activity is performed as a response to an event
received in a state. Activities are performed on a
transition, at the beginning, end or inside a state.
• Notation: “/ activity name” following a
triggering event name.

right button pressed/show popup menu


Idle Menu_visible
right button released / erase popup menu

cursor moved / highlight menu item

• Do-activity is an operation, which has duration.


- Do-activity is assigned to the state, it cannot be
assigned to a transition.
- Do-activity contains continuous operations
(which run infinitely) as well as sequential
operations (which terminate by themselves).
- Notation: “do/ A” in a state symbol.
- Do-activity A starts at a beginning of a state.

Paper jam in printer


do/flash warning light

45
- Do-activity can be interrupted by an event
received during its execution.
Ex.: a robot which is moving a part can
encounter an obstacle which stops moving.
• Input and output activities are performed at the
beginning or end of a state. Input activity is an
equivalent to the activity at an input transition.

depress/motor up Opening door open/motor off

Closed depress/motor up Open

door closed/motor off Closing depress/motor down

depress Opening door open


entry/motor up

Closed Open
entry/motor off depress entry/motor off

door closed depress


Closing
entry/motor down

46
- If there is an activity on input transition, this
activity is executed first.
- Input activities are indicated inside a state
symbol and have a form entry/activity name.
- Output activities are indicated inside a state
symbol and have a form exit/activity name.
- If a state is terminated by an output transition,
the output activities are executed first.
- If several activities concern a state, then these
are executed in the following order:
- Activities at input transition
- Input activities
- Do-activities
- Output activities
- Activities at output transition.
- When a do-activity is interrupted, the output
activity is still executed.
- Besides entry and exit also other events and
their activities can occur in a state.
Example:
Closed
shutdown/motor off

47
• Automatic (completion) transition.
- Often the only task of the state is to conduct a
sequential activity.
- A transition is automatically fired after
completing activity if transition is not labelled
by an event name and (eventual) condition
holds.
- Unlabeled transitions are called terminal
transitions.
- If a condition(s) is not satisfied at the terminal
transition(s), then “freezing” in the state
occurs. We should look-out for this possibility.
• Sending signals
- Object can perform an activity by sending a
signal to another object – it is object
interaction.
- Activity send target.S(attributes) sends a signal
S (with given attributes) to a target object.
- If a target is a set of objects, each of them
obtains a separate copy of a signal and each
reacts independently.
- If object can receive signals from several objects
then timing of received signals can influence a
final state – “racing conditions”. Simultaneous
occurrence of two events is never meaningfull in
practice.

48
• Basic UML notation of the state diagrams:
event1(attributes1)[condition1]/ effect
State1 State2
do/ activity1 …
event2/effect

Nested state diagrams


• SDs are often ctriticized for being unpractical for
n
large tasks. (Problem of 2 states at n
independent attributes).
• All complex systems contain a lot of redundance,
by which we can simplify SD.
• By splitting SD at n independent state machines
we need only 2n states.
• State diagrams can be structured with use of
generalization and aggregation.
• Generalization is an analogy to expanding of
nested activities (analogy with „subprograms“).
• We can create a high level (root) state diagram,
where individual states can be expressed by a
separate state diagram (sub-machine).
• UML notation is state name : sub-machine name

49
Example – vending machine:

VendingM achine
Coins in(am ount)
Collecting m oney
Idle Insert coin/add to balance
cancel/refund coins
select(item ) [ change<0]
[item em pty]
[zůstatek=0]
Checking
do / test item and com pute change
[ change=0] [change>0]

Dispense:DispenseItem do / m ake change

DispenseItem

do / move arm to correct row

arm ready

do / move arm to correct column

arm ready

do / push item off shelf

pushed

50
Generalization of state
• Generalization is “or” relationship.
• Object in a certain state in a root SD must be in
exactly one state in the nested SDs.
(i.e. it must be in the first or in the second or in
one of the following states).
• States can have sub-states, which inherit all input
transitions of their super-states.
Ex.: A phone-line model can be simplified into
two states: “idle” and “active”.
PhoneLine
offHook
Idle Active
onHook

CarTransmission
push R
default
Neutral Reverse
push N
push F
push N

Forward
stop
stop

default upshift upshift


First Second Third
downshift downshift

51
Generalization of events (signals)
• Events can be arranged into a generalization
hierarchy with inheritance of events attributes.
• Each real event is a leaf of this hierarchical tree.
• Inherited event attributes are listed in the bottom
part of the symbol (box).

«signal»
UserInput
device

«signal» «signal»
MouseButton KeyboardChar
location character

«signal» «signal» «signal» «signal»


Pressed Released Graphic Control

«signal» «signal» «signal»


Space Alphanumer. Punctuation

52
Concurence
• Dynamic model describes a set of concurent
objects, each with its SD.
• Objects in a system are inherently concurent and
they can independently change their state.
• SD for an assembly is a set of SDs, one for each
component.
• Aggregation enables to a state (for an assembly),
to be decomposed into orthogonal components
(parts), with a limited interaction amongst them.
• Aggregation is an equivalent of state concurency.
• Aggregated state corresponds to combination of
states of all components.
• Aggregation is “and” relationship.
Aggregated state is one state from the first SD and
one state from the second SD and one state from
every next SD.

53
Car

Ignition Transmission Brakes Gas

Ignition
Turn a key to start
[Transmission in Neutral] Release a key

Off Starting On

Turn a key to stop

AutomaticTransmission
R
default
neutral reverse
N
F N

forward
stop
stop

default upshift upshift


first second third
downshift downshift

Gas Gas pedal pushed Brake Brake pedal pushed

Off On Off On

Gas pedal released Brake pedal released

54
Synchronization of concurent activities
• Sometimes object must concurrently conduct two
or more activities.
• Activity in a SD can be decomposed into a lower
level SD.
• We can also model splitting of control and
merging control of concurrent activities:

Cash dispenser

Ready do/dispense cash


Reset
Setting up
do/eject card

Practical recommendations
• Not all objects need a state model. ⇒ We shall
build a state diagram only for classes with a
meaningfull dynamic behavior (when object
reacts differently at various events and it has
more than a single state).
• Use only relevant attributes to define a state. SD
neednot use all attributes of the object model.
• Check consistence of shared events in different
SDs, in order that a resulting dynamic model was
correct.

55
• When the state has several input transitions and
these transitions trigger the same activity, use
prefferably entry activity in a state instead of
repeated referring of the activity on a transition.
Proceed analogically for exit activity.
• Beware of conditions on transition, to avoid
„freezing“ of an object in a state.
• Beware of unwanted racing conditions (when a
state receives events from several objects).
• Use nested state diagrams, when the same
transition holds for several states.
• Try to create state models of subclasses
independently from state models of their
superclasses. SD of a subclass focuses at
specific/unique attributes of this subclass.

56

Você também pode gostar