UML Diagrams
Class Diagram
The UML Class diagram is a graphical notation used to construct and visualize object-oriented systems. A
class diagram in the Unified Modeling Language (UML) is a type of static structure diagram that describes
the structure of a system by showing the system's:
    • classes,
    • their attributes,
    • operations (or methods),
    • and the relationships among objects.
A Class is a blueprint for an object. Objects and classes go hand in hand. We can't talk about one without
talking about the other. And the entire point of Object-Oriented Design is not about objects, it's about classes,
because we use classes to create objects. So, a class describes what an object will be, but it isn't the object
itself.
In fact, classes describe the type of objects, while objects are usable instances of classes. Each Object was
built from the same set of blueprints and therefore contains the same components (properties and methods).
The standard meaning is that an object is an instance of a class and object - Objects have states and behaviors.
Example
   • A dog has states - color, name, breed as well as behaviors -wagging, barking, eating. An object is an
     instance of a class.
UML Class Notation
A class represent a concept which encapsulates state (attributes) and behavior (operations). Each attribute
has a type. Each operation has a signature. The class name is the only mandatory information.
Class Name:
   • The name of the class appears in the first partition.
Class Attributes:
   • Attributes are shown in the second partition.
   • The attribute type is shown after the colon.
   • Attributes map onto member variables (data members) in code.
Class Operations (Methods):
   • Operations are shown in the third partition. They are services the class provides.
   • The return type of a method is shown after the colon at the end of the method signature.
   • The return type of method parameters are shown after the colon following the parameter name.
       Operations map onto class methods in code
Class Visibility
The +, - and # symbols before an attribute and operation name in a class denote the visibility of the attribute
and operation.
   •   + denotes public attributes or operations
   •   - denotes private attributes or operations
   •   # denotes protected attributes or operations
Class Relationships
A class may be involved in one or more relationships with other classes. A relationship can be one of the
following types: (Refer to the figure on the right for the graphical representation of relationships).
 Relationship Type                                                            Graphical Representation
Inheritance (or Generalization):
   • Represents an "is-a" relationship.
   • An abstract class name is shown in italics.
   • SubClass1 and SubClass2 are specializations of Super Class.
   • A solid line with a hollow arrowhead that point from the child
       to the parent class
Simple Association:
   • A structural link between two peer classes.
   • There is an association between Class1 and Class2
   •   A solid line connecting two classes
Aggregation:
A special type of association. It represents a "part of" relationship.
   • Class2 is part of Class1.
   • Many instances (denoted by the *) of Class2 can be associated
       with Class1.
   • Objects of Class1 and Class2 have separate lifetimes.
   • A solid line with an unfilled diamond at the association end
       connected to the class of composite
Composition:
A special type of aggregation where parts are destroyed when the whole
is destroyed.
    • Objects of Class2 live and die with Class1.
    • Class2 cannot stand by itself.
    • A solid line with a filled diamond at the association connected
        to the class of composite
Dependency:
   • Exists between two classes if the changes to the definition of
      one may cause changes to the other (but not the other way
      around).
   • Class1 depends on Class2
   • A dashed line with an open arrow
Cardinality
Cardinality is expressed in terms of:
   • one to one
   • one to many
   •   many to many
Relationship Names
   •   Names of relationships are written in the middle of the association line.
   •   Good relation names make sense when you read them out loud:
           • "Every spreadsheet contains some number of cells",
           • "an expression evaluates to a value"
   •   They often have a small arrowhead to show the direction in which direction to read the relationship,
       e.g., expressions evaluate to values, but values do not evaluate to expressions.
Relationship - Roles
   •   A role is a directional purpose of an association.
   •   Roles are written at the ends of an association line and describe the purpose played by that class in the
       relationship.
           • E.g., A cell is related to an expression. The nature of the relationship is that the expression is
               the formula of the cell.
Example Class Diagram to draw
                                             Activity diagram
Activity diagram is another important behavioral diagram in UML diagram to describe dynamic aspects of
the system. Activity diagram is essentially an advanced version of flow chart that modeling the flow from
one activity to another activity.
Activity Diagrams describe how activities are coordinated to provide a service which can be at different levels
of abstraction. Typically, an event needs to be achieved by some operations, particularly where the operation is
intended to achieve a number of different things that require coordination, or how the events in a single use case
relate to one another, in particular, use cases where activities may overlap and require coordination. It is also
suitable for modeling how a collection of use cases coordinates to represent business workflows
    1. Identify candidate use cases, through the examination of business workflows
    2. Identify pre- and post-conditions (the context) for use cases
    3. Model workflows between/within use cases
    4. Model complex workflows in operations on objects
    5. Model in detail complex activities in a high level activity Diagram
 Notation Description                                                              UML Notation
Activity
Is used to represent a set of actions
Action
A task to be performed
Control Flow
Shows the sequence of execution
Object Flow
Show the flow of an object from one activity (or action) to another activity
(or action).
Initial Node
Portrays the beginning of a set of actions or activities
Activity Final Node
Stop all control flows and object flows in an activity (or action)
Object Node
Represent an object that is connected to a set of Object Flows
Decision Node
Represent a test condition to ensure that the control flow or object flow only
goes down one path
Merge Node
Bring back together different decision paths that were created using a
decision-node.
Fork Node
Split behavior into a set of parallel or concurrent flows of activities (or
actions)
Join Node
Bring back together a set of parallel or concurrent flows of activities (or
actions).
Swimlane and Partition
A way to group activities performed by the same actor on an activity
diagram or to group activities in a single thread
Activity Diagram - Learn by Examples
A basic activity diagram - flowchart like
Activity Diagram - Modeling a Word Processor
The activity diagram example below describes the workflow for a word process to create a document through
the following steps:
    • Open the word processing package.
    • Create a file.
    • Save the file under a unique name within its directory.
    • Type the document.
    • If graphics are necessary, open the graphics package, create the graphics, and paste the graphics into the
        document.
    • If a spreadsheet is necessary, open the spreadsheet package, create the spreadsheet, and paste the
        spreadsheet into the document.
    • Save the file.
  •   Print a hard copy of the document.
  •   Exit the word processing package.
Activity Diagram Example 2
State Machine Diagram
State machine diagram typically are used to describe state-dependent behavior for an object. An object
responds differently to the same event depending on what state it is in. State machine diagrams are usually
applied to objects but can be applied to any element that has behavior to other entities such as: actors, use cases,
methods, subsystems systems and etc. and they are typically used in conjunction with interaction diagrams
(usually sequence diagrams).
For example:
Consider you have $100,000 in a bank account. The behavior of the withdraw function would be: balance :=
balance – withdraw Amount; provided that the balance after the withdrawal is not less than $0; this is true
regardless of how many times you have withdrawn money from the bank. In such situations, the withdrawals
do not affect the abstraction of the attribute values, and hence the gross behavior of the object remains
unchanged.
However, if the account balance would become negative after a withdrawal, the behavior of the withdraw
function would be quite different. This is because the state of the bank account is changed from positive to
negative; in technical jargon, a transition from the positive state to the negative state is fired.
The abstraction of the attribute value is a property of the system, rather than a globally applicable rule. For
example, if the bank changes the business rule to allow the bank balance to be overdrawn by 2000 dollars, the
state of the bank account will be redefined with condition that the balance after withdrawal must not be less
than $2000 in deficit.
Note That:
    • A state machine diagram describes all events (and states and transitions for a single object)
    • A sequence diagram describes the events for a single interaction across all objects involved
Basic Concepts of State Machine Diagram
What is a State?
Rumbaugh defines that:
"A state is an abstraction of the attribute values and links of an object. Sets of values are grouped together into
a state according to properties that affect the gross behavior of the object."
State Notation
Characteristics of State Machine Notations
There are several characteristics of states in general, regardless of their types:
   • A state occupies an interval of time.
   • A state is often associated with an abstraction of attribute values of an entity satisfying some
       condition(s).
   • An entity changes its state not only as a direct consequence of the current input, but it is also dependent
       on some past history of its inputs.
State
A state is a constraint or a situation in the life cycle of an object, in which a constraint holds, the object executes
an activity or waits for an event.
A state machine diagram is a graph consisting of:
    • States (simple states or composite states)
    • State transitions connecting the states
Example:
Characteristics of State
    • State represent the conditions of objects at certain points in time.
    • Objects (or Systems) can be viewed as moving from state to state
    • A point in the lifecycle of a model element that satisfies some condition, where some particular action
        is being performed or where some event is waited
Initial and Final States
    • The initial state of a state machine diagram, known as an initial pseudo-state, is indicated with a solid
        circle. A transition from this state will show the first real state
    • The final state of a state machine diagram is shown as concentric circles. An open loop state machine
        represents an object that may terminate before the system terminates, while a closed loop state machine
        diagram does not have a final state; if it is the case, then the object lives until the entire system terminates.
Example:
Events
An event signature is described as Event-name (comma-separated-parameter-list). Events appear in the internal
transition compartment of a state or on a transition between states. An event may be one of four types:
    1. Signal event - corresponding to the arrival of an asynchronous message or signal
    2. Call event - corresponding to the arrival of a procedural call to an operation
    3. Time event - a time event occurs after a specified time has elapsed
    4. Change event - a change event occurs whenever a specified condition is met
Characteristics of Events
    • Represents incidents that cause objects to transition from one state to another.
    • Internal or External Events trigger some activity that changes the state of the system and of some of its
        parts
    • Events pass information, which is elaborated by Objects operations. Objects realize Events
    • Design involves examining events in a state machine diagram and considering how those events will be
        supported by system objects
Transition
Transition lines depict the movement from one state to another. Each transition line is labeled with the event that
causes the transition.
    • Viewing a system as a set of states and transitions between states is very useful for describing complex
        behaviors
    • Understanding state transitions is part of system analysis and design
    • A Transition is the movement from one state to another state
    • Transitions between states occur as follows:
             1. An element is in a source state
             2. An event occurs
             3. An action is performed
             4. The element enters a target state
    • Multiple transitions occur either when different events result in a state terminating or when there are
        guard conditions on the transitions
    • A transition without an event and action is known as automatic transitions
Actions
Action is an executable atomic computation, which includes operation calls, the creation or destruction of
another object, or the sending of a signal to an object. An action is associated with transitions and during which
an action is not interruptible - e.g., entry, exit
Activity
Activity is associated with states, which is a non-atomic or ongoing computation. Activity may run to
completion or continue indefinitely. An Activity will be terminated by an event that causes a transition from
the state in which the activity is defined
Characteristics of Action and Activities
    • States can trigger actions
    • States can have a second compartment that contains actions or activities performed while an entity is in
        a given state
    • An action is an atomic execution and therefore completes without interruption
    • Five triggers for actions: On Entry, Do, On Event, On Exit, and Include
    • An activity captures complex behavior that may run for a long duration - An activity may be interrupted
        by events, in which case it does not complete occur when an object arrives in a state.
Simple State Machine Diagram Notation
Entry and Exit Actions
Entry and Exit actions specified in the state. It must be true for every entry / exit occurrence. If not, then you
must use actions on the individual transition arcs
   • Entry Action executed on entry into state with the notation: Entry / action
   • Exit Action executed on exit from state with the notation: Exit / action
Example - Entry / Exit Action (Check Book Status)
This example illustrates a state machine diagram derived from a Class - "BookCopy":
Note:
    1. This state machine diagram shows the state of an object myBkCopy from a BookCopy class
    2. Entry action : any action that is marked as linked to the entry action is executed whenever the given state
        is entered via a transition
    3. Exit action : any action that is marked as linked to the exit action is executed whenever the state is left
        via a transition
Substates
A simple state is one which has no substructure. A state which has substates (nested states) is called a composite
state. Substates may be nested to any level. A nested state machine may have at most one initial state and one
final state. Substates are used to simplify complex flat state machines by showing that some states are only
possible within a particular context (the enclosing state).
Substate Example - Heater
State Machine Diagrams are often used for deriving testing cases, here is a list of possible test ideas:
    • Idle state receives Too Hot event
    • Idle state receives Too Cool event
    • Cooling/Startup state receives Compressor Running event
    • Cooling/Ready state receives Fan Running event
    • Cooling/Running state receives OK event
    • Cooling/Running state receives Failure event
    • Failure state receives Failure Cleared event
   •    Heating state receives OK event
   •    Heating state receives Failure event
History States
Unless otherwise specified, when a transition enters a composite state, the action of the nested state machine
starts over again at the initial state (unless the transition targets a substate directly). History states allow the
state machine to re-enter the last substate that was active prior to leaving the composite state. An example
of history state usage is presented in the figure below.
Concurrent State
As mentioned above, states in state machine diagrams can be nested. Related states can be grouped together
into a single composite state. Nesting states inside others is necessary when an activity involves concurrent sub-
activities. The following state machine diagram models an auction with two concurrent substates: processing
the bid and authorizing the payment limit.
Concurrent State Machine Diagram Example - Auction Process
In this example, the state machine first entering the Auction requires a fork at the start into two separate start
threads. Each substate has an exit state to mark the end of the thread. Unless there is an abnormal exit (Canceled
or Rejected), the exit from the composite state occurs when both substates have exited.
Example State Diagram
Sequence Diagram
Sequence Diagrams are interaction diagrams that detail how operations are carried out. They capture the
interaction between objects in the context of a collaboration. Sequence Diagrams are time focus and they
show the order of the interaction visually by using the vertical axis of the diagram to represent time what
messages are sent and when.
Sequence Diagrams captures:
    • the interaction that takes place in a collaboration that either realizes a use case or an operation (instance
       diagrams or generic diagrams)
    • high-level interactions between user of the system and the system, between the system and other
       systems, or between subsystems (sometimes known as system sequence diagrams)
Purpose of Sequence Diagram
    • Model high-level interaction between active objects in a system
    • Model the interaction between object instances within a collaboration that realizes a use case
    • Model the interaction between objects within a collaboration that realizes an operation
    • Either model generic interactions (showing all possible paths through the interaction) or specific
       instances of a interaction (showing just one path through the interaction)
Sequence Diagrams at a Glance
Sequence Diagrams show elements as they interact over time and they are organized according to object
(horizontally) and time (vertically):
Object Dimension
    • The horizontal axis shows the elements that are involved in the interaction
   •   Conventionally, the objects involved in the operation are listed from left to right according to when they
       take part in the message sequence. However, the elements on the horizontal axis may appear in any order
Time Dimension
    • The vertical axis represents time proceedings (or progressing) down the page.
Note that: Time in a sequence diagram is all a about ordering, not duration. The vertical space in an interaction
diagram is not relevant for the duration of the interaction.
Sequence Diagram Example: Hotel System
Sequence Diagram is an interaction diagram that details how operations are carried out -- what messages are
sent and when. Sequence diagrams are organized according to time. The time progresses as you go down the
page. The objects involved in the operation are listed from left to right according to when they take part in the
message sequence.
Below is a sequence diagram for making a hotel reservation. The object initiating the sequence of messages is
a Reservation window.
Note That: Class and object diagrams are static model views. Interaction diagrams are dynamic. They describe
how objects collaborate.
Sequence Diagram Notation
 Notation Description                                                     Visual Representation
Actor
   •   a type of role played by an entity that interacts with the subject
       (e.g., by exchanging signals and data)
   • external to the subject (i.e., in the sense that an instance of an
       actor is not a part of the instance of its corresponding subject).
   • represent roles played by human users, external hardware, or
       other subjects.
Note that:
   • An actor does not necessarily represent a specific physical
       entity but merely a particular role of some entity
   • A person may play the role of several different actors and,
       conversely, a given actor may be played by multiple different
       person.
Lifeline
    • A lifeline represents an individual participant in the Interaction.
Activations
   • A thin rectangle on a lifeline) represents the period during
       which an element is performing an operation.
   • The top and the bottom of the of the rectangle are aligned with
       the initiation and the completion time respectively
Call Message
   • A message defines a particular communication between
      Lifelines of an Interaction.
   • Call message is a kind of message that represents an invocation
      of operation of target lifeline.
Return Message
   • A message defines a particular communication between
      Lifelines of an Interaction.
   • Return message is a kind of message that represents the pass of
      information back to the caller of a corresponded former
      message.
Self Message
    • A message defines a particular communication between
      Lifelines of an Interaction.
    • Self message is a kind of message that represents the invocation
      of message of the same lifeline.
Recursive Message
   • A message defines a particular communication between
      Lifelines of an Interaction.
   • Recursive message is a kind of message that represents the
      invocation of message of the same lifeline. It's target points to
      an activation on top of the activation where the message was
      invoked from.
Create Message
   • A message defines a particular communication between
      Lifelines of an Interaction.
   • Create message is a kind of message that represents the
      instantiation of (target) lifeline.
Destroy Message
   • A message defines a particular communication between
      Lifelines of an Interaction.
   • Destroy message is a kind of message that represents the
      request of destroying the lifecycle of target lifeline.
Duration Message
   • A message defines a particular communication between
      Lifelines of an Interaction.
   • Duration message shows the distance between two time instants
      for a message invocation.
Note
A note (comment) gives the ability to attach various remarks to elements. A comment carries no semantic force, but
may contain information that is useful to a modeler.
Message and Focus of Control
  • An Event is any point in an interaction where something occurs.
  • Focus of control: also called execution occurrence, an execution occurrence
      •   It shows as tall, thin rectangle on a lifeline)
      •   It represents the period during which an element is performing an operation. The top and the bottom of
          the rectangle are aligned with the initiation and the completion time respectively.
Sequence Fragments
   • UML 2.0 introduces sequence (or interaction) fragments. Sequence fragments make it easier to create
      and maintain accurate sequence diagrams
   • A sequence fragment is represented as a box, called a combined fragment, which encloses a portion of
      the interactions within a sequence diagram
   • The fragment operator (in the top left cornet) indicates the type of fragment
   • Fragment types: ref, assert, loop, break, alt, opt, neg
Operator Fragment Type
alt         Alternative multiple fragments: only the one whose condition is true will execute.
            Optional: the fragment executes only if the supplied condition is true. Equivalent to an alt
opt
            only with one trace.
par         Parallel: each fragment is run in parallel.
            Loop: the fragment may execute multiple times, and the guard indicates the basis of
loop
            iteration.
region      Critical region: the fragment can have only one thread executing it at once.
neg         Negative: the fragment shows an invalid interaction.
            Reference: refers to an interaction defined on another diagram. The frame is drawn to cover
ref
            the lifelines involved in the interaction. You can define parameters and a return value.
sd        Sequence diagram: used to surround an entire sequence diagram.
Note That:
   • It is possible to combine frames in order to capture, e.g., loops or branches.
   • Combined fragment keywords: alt, opt, break, par, seq, strict, neg, critical, ignore, consider, assert and
      loop.
   • Constraints are usually used to show timing constraints on messages. They can apply to the timing of
      one message or intervals between messages.
Combined Fragment Example
Sequence Diagram for Modeling Use Case Scenarios
User requirements are captured as use cases that are refined into scenarios. A use case is a collection of
interactions between external actors and a system. In UML, a use case is:
"the specification of a sequence of actions, including variants, that a system (or entity) can perform, interacting
with actors of the system."
A scenario is one path or flow through a use case that describes a sequence of events that occurs during one
particular execution of a system which is often represented by a sequence diagram.
Sequence Diagram - Model before Code
Sequence diagrams can be somewhat close to the code level, so why not just code up that algorithm rather than
drawing it as a sequence diagram?
   • A good sequence diagram is still a bit above the level of the real code
   • Sequence diagrams are language neutral
   • Non-coders can do sequence diagrams
   • Easier to do sequence diagrams as a team
   • Can be used for testing and/or UX Wireframing