Download as pdf or txt
Download as pdf or txt
You are on page 1of 79

Module 6: Object-Oriented Design – UML Diagrams in Design

Software Engineering
Computer Science
Academic Year 2023/2024

Gerard Albà Soler

1
Contents
1. Introduction
• What will we learn
2. Object Oriented Design
- Design principles
- Design patterns
- Operation contract and Class diagram normalization
- Object responsibilities assignment
- Behavioral modeling. Sequence diagram and State diagram
- Software Architecture
- Components and Packages
1. Introduction
OO Design phase
What will we learn?
• Design is the bridge between the analysis and implementation of the software. OOD is a design model
that is considered as a blueprint for software construction
ü A design should exhibit an architecture (software architecture)
ü A design should be modular: the software should be logically partitioned into subsystems
ü A design should contain distinct representations of data, architecture, interfaces, and components
ü A design should lead to data structures that are appropriate for the classes to be implemented and
are drawn from recognizable data patterns
ü A design should lead to components that exhibit independent functional characteristics
ü A design should lead to interfaces that reduce the complexity of connections between
components and with the external environment
ü A design should be represented using a notation that effectively communicates its meaning
1. Introduction
OO Design phase
What will we learn?
• Design fundamental concepts:
ü Abstraction: data, procedure, control
ü Architecture: the overall structure of the software
ü Patterns: ”conveys the essence” of a proven design solution
ü Separation of concerns: any complex problem can be more easily handled if it is
subdivided into pieces (Subsystems/modules, Objects)
ü Modularity: compartmentalization of data and function
ü Hiding: controlled interfaces
ü Functional Independence: single-minded function and low coupling
ü Refinement: elaboration of detail for all abstractions
ü Refactoring: a reorganization technique that simplifies the design
ü Design Classes: provide design detail that will enable analysis classes to be implemented
1. Introduction
OO Design phase

• UML diagrams specifically used in these Desing layers: machine state (one Object),
sequence diagrams (several Classes); component, package and deployment diagrams.
We have also studied in the previous section design principles and patterns to improve
our design of classes.
1. Introduction
OO Design phase
What will we learn?

• The Subsystem layer: it represents the subsystem that enables software to achieve user
requirements and implement technical frameworks that meet user needs.
• The Class and Object layer: it represents the class hierarchies that enable the system to
develop using generalization and specialization. This layer also represents each object.
• The Message layer: this layer deals with how objects interact with each other. It includes
messages sent between objects, method calls, and the flow of control within the system.
• The Responsibilities layer: it focuses on the responsibilities of individual objects. This
includes defining the behavior of each class, specifying what each object is responsible for,
and how it responds to messages. This means that the object must have the capability to
perform required services itself or at least know how to find and invoke these services.
1. Introduction
What will we learn?
1. Introduction
What will we learn?
OOA/D Design

Exercises UML in Design

OOA/D

Sequence State Machine


Diagrams Diagram

Exercises
1. Introduction
• Book References

ü Object-Oriented Software Engineering Using UML, Patterns, and Java.


3rd ed. B. Bruegge et al. Ed Pearson
ü Object-Oriented Modeling and Design with UML. 2nd ed. M. Blaha et al.
Ed Pearson
2.3 UML Diagrams in Design
• Remember the following -simplified summary- of the process of going from requirements to object-
oriented design. The steps are often iterated many times as the design is refined.

Step OOA/D Description


1. Perform a use case • Determine product requirements
analysis
• These are real-world entities that would be involved in performing the tasks of
2. Identify the the use case if it were performed manually, such as customer, database, cash
conceptual (domain) register, statement, etc. Often the secondary actors give rise to classes that
classes are needed to interface with the external entity.

• Classes (not real-world) that would help organize the tasks to be


performed. These computer software classes may have no real-world
3. Identify any counterpart. For example you might include a session manager (controller)
software classes class to supervise the user interaction, or you may need classes to perform
data manipulations
2.3 UML Diagrams in Design
Step OOA/D Description
• Think about how to assign responsibilities in such a way as to
simplify your design. We need to determine what classes have the
4. Assign responsibilities to
classes responsibility of creating and destroying other classes. Make use of
inheritance whenever appropriate

• Construct interaction diagrams (sequence diagrams or collaboration


5. Construct interaction diagrams) for your use cases. You may find that it is useful to add
diagrams additional classes to perform the use cases

• Include all the associations that are needed for your interaction
diagrams to work.
6. Construct a class diagram • Supply any operations and attributes needed to implement your
interaction diagrams
2.3 UML Diagrams in Design
Step OOA/D Description

7. Construct state • As needed to work out the details of any complex behaviors
and/or activity
diagrams

• Look at your design for possible improvements to the object-oriented design,


8. Improvements to for example making more use of inheritance, and changing class
the object-oriented responsibilities to decrease coupling or increase cohesion. Modify your UML
design diagrams whenever you add new capabilities that were not in the original
diagrams

• Implement the methods needed, again making changes to your UML diagrams
9. Implement the as you identify new operations and interactions that were not previously in
methods needed the diagram
2.3 UML Diagrams in Design
State Machine Diagram
(State-Chart, State Transition, State Machine)

üState Lifecycle of objects


üBehaviour of operations

• Use State machines when:


ü At an early stage of software development
ü When behaviour of an object (lifecycle) or operation is not well understood yet

• Do not use State machines: when several objects are involved (interaction diagrams
are better. Will cover them later in this section of Module 6)
2.3 UML Diagrams in Design
State Machine Diagram
(State-Chart, State Transition, State Machine)

• Labelled, finite graph (cycles possible)

• The States are Nodes of the graph


• Labelled with: name, do-, entry-, exit-action, etc
• Initial and final states have special shapes

• Transitions are Edges of the graph


• Labelled with: event, guard, action, etc
2.3 UML Diagrams in Design
State Machine Diagram

• The goal is to describe the dynamic behaviour of an entity (usually an Object life)
• It can describe any level of abstraction (system, component, object...)
• It uses:
• States of the entity (drawn as a rectangle with rounded corners)
• Transition between states (shown using arrows with the actions performed)
• Events that trigger these transitions
2.3 UML Diagrams in Design
State Machine Diagram
• State: period of time during the life of an entity in which a set of conditions are
satisfied
• Transition: state change triggered by an event
• It’s a summary of the dynamics of the system
• The name of each state (inside rectangles) must be unique
2.3 UML Diagrams in Design
State Machine Diagram

• During analysis:
ü Dynamic behaviour seen from outside
ü Describe the use cases and alternative scenarios
ü Events are actions performed by actors

• During design:
ü Dynamic behaviour of a single object
ü Events are method calls
2.3 UML Diagrams in Design
State Machine Diagram
• Initial state: we typically use a black filled circle represent the initial state of a
System or a Class.
2.3 UML Diagrams in Design
State Machine Diagram
• Transition: we usually use a solid arrow to represent the transition or change of
control from one state to another. The arrow is labelled with the event which
causes the change in state.
2.3 UML Diagrams in Design
State Machine Diagram

• The transition action is the reaction of the system to an event, and it can be:
üAssign a value
üCalling an operation
üSending a signal
üCreation or destruction of objects

• When an event arise, if the condition is true, the action is performed:


2.3 UML Diagrams in Design
State Machine Diagram
• Self transition: we use a solid arrow pointing back to the state itself to represent a
self transition. There might be scenarios when the state of the object does not
change upon the occurrence of an event. We use self transitions to represent such
cases.
2.3 UML Diagrams in Design
State Machine Diagram
• Composite state: we use a rounded rectangle to represent a composite state also.
We represent a state with internal activities using a composite state.
2.3 UML Diagrams in Design
State Machine Diagram
• Final State: we use a filled circle within a circle notation to represent the final state
in a state machine diagram.
2.3 UML Diagrams in Design
State Machine Diagram
• Fork: we use a solid rectangular bar to represent a Fork notation with incoming
arrow from the parent state and outgoing arrows towards the newly created
states. We use the fork notation to represent a state splitting into two or more
concurrent states.
2.3 UML Diagrams in Design
State Machine Diagram
• Join: we use a solid rectangular bar to represent a Join notation with incoming
arrows from the joining states and outgoing arrow towards the common goal
state. We use the join notation when two or more states concurrently converge
into one on the occurrence of an event or events.
2.3 UML Diagrams in Design
State Machine Diagram
• Example
2.3 UML Diagrams in Design
State Machine Diagram

• Event types: the expected events are all the events that may trigger a state
transition.
ü Signal event: asynchronous message or signal.
ü Call event: calling an operation (for example the ones defined in the class
diagram).
ü Condition event: when (condition) —> condition is a Boolean expression that
is constantly evaluated until it’s true.
ü A Guard condition is a boolean condition that is evaluated when a transition
initiates. A transition with a guard condition occurs when the guard condition
is evaluated to be true.
ü Time event: Relative date: after (Time); Absolute date: when (date=Date).
2.3 UML Diagrams in Design
Example: State Machine Diagram – Bank ATM

• The customer must pass authentication before withdrawing money.


2.3 UML Diagrams in Design
Example: State Machine Diagram – Bank ATM

• The customer must pass authentication before withdrawing money.


• Authentication is done bychecking a PIN.
2.3 UML Diagrams in Design
Example: State Machine Diagram – Bank ATM

• The customer must pass authentication before withdrawing money.


• Authentication is done bychecking a PIN.
• The PIN can be correct or not.
2.3 UML Diagrams in Design
Example: State Machine Diagram – Bank ATM

• The customer must pass authentication before withdrawing money.


• Authentication is done bychecking a PIN.
• The PIN can be correct or not.
• Unseccessful attempts are counted.
2.3 UML Diagrams in Design
Example: State Machine Diagram – Bank ATM

• The customer must pass authentication before withdrawing money.


• Authentication is done bychecking a PIN.
• The PIN can be correct or not.
• Unseccessful attempts are counted.
• If the counter exceeds a limit, the customer is rejected.
2.3 UML Diagrams in Design
Example: State Machine Diagram – Bank ATM

• The customer must pass authentication before withdrawing money.


• Authentication is done bychecking a PIN.
• The PIN can be correct or not.
• Unseccessful attempts are counted.
• If the counter exceeds a limit, the customer is rejected.
2.3 UML Diagrams in Design
Example: State Machine Diagram –
Bank ATM

• An alternative notation: using the


composite state (Authentication),
internal transitions (CheckPIN),
and Entry and Exit Actions
2.3 UML Diagrams in Design
Activity 6.3.1
Let’s consider the following machine state UML diagram for a chess game.
Explain the relationship of the different elements of such a diagram: initial state, final state, states,
transtions, events, with the corresponding statement below.

a) A chess game consists of alternate moves of


Black and White.
b) White moves first.
c) The game can end both when it is White's and
when it is Black's turn.
d) The moving player can end the game: winning
(checkmate),
e) loosing (resign),
f) or with a draw.
2.3 UML Diagrams in Design
Activity 6.3.2
Let’s consider the following machine state UML diagram for a student graduate program.
Explain the relationship of the different elements of such a diagram: initial state, final state, states,
transtions, events, with the corresponding statement below.

a) A student must complete the basic level before


entering the advanced level.
b) After both levels, the student has to pass five
examinations.
c) An examination can be retaken at most twice.
d) After the third failed attempt the student's
registration is cancelled.
2.3 UML Diagrams in Design
Sequence diagrams
(Event diagrams, Event scenarios)

• Sequence diagrams are one of the most widely use UML diagrams. During the design phase of
software development, sequence diagrams help developers and architects plan and understand how
different components and objects will interact to accomplish specific functionalities. They provide a
blueprint for the system’s behavior.
• They allow a temporal (dynamic, evolution over time) representation of interactions between two or
more entities within a scenario or use case.
• Capture the exchange messages between classes and actors and the timeline of events. These
diagrams focus on showing detailed interactions, such as which objects are involved in an interaction,
which methods are invoked, and the sequence of events.
2.3 UML Diagrams in Design
• Two read directions:
ü Horizontally : Arrows indicate
direction of the message.
ü Vertically : Chronological
order of the messages.
• Elements of a sequence diagram:
ü Participants
ü Lifeline
ü Interaction messages
ü Activation or execution
specification
2.3 UML Diagrams in Design

• Participants: live objects, we use the


notation “ObjectName : Class”
• Lifeline: from top to bottom showing
the object is alive.
• Interaction messages: arrow that
indicates an operation call. The dotted
arrow is the response to the operation
call.
• Activation bar: object is alive, waiting
for the execution to be completed.
2.3 UML Diagrams in Design
• Special case: call to the constructor of a
class
• The object name is aligned with the
message that created it
• A constructor call always returns the object
instance to the caller
• When there is a need to explicitly destroy
an object that can be done by adding a
cross in the objects lifeline
• Ex: the creation of a new order on a
ecommerce website would require a new
object of Order class to be created
2.3 UML Diagrams in Design
• Call to an internal operation (self message)
can be done by sending an arrow to its
lifeline
• Execution specification for this new
operation is overlaid to the previous one
• Ex: Consider a scenario where the device
wants to access its webcam. Such a
scenario is represented using a self
message
2.3 UML Diagrams in Design

• Sequence diagrams help to


identify class methods.
• Messages to an object can
be translated by methods
inside the object.
• Message response can be
translated as a return value
of the method.
2.3 UML Diagrams in Design

• Opt: option. It’s like an if


without an else.

• Alt: alternative. One or more


alternate conditions. If the
first condition is not true, act
as an if-else condition.

• Loop: block of messages that


continue to get passed as the
condition is true.
2.3 UML Diagrams in Design
• Example: system sequence diagram of a basic sales scenario
2.3 UML Diagrams in Design
• Example: a sequence diagram for making a hotel reservation. The object
initiating the sequence of messages is a Reservation window.
2.3 UML Diagrams in Design
Example: Sequence diagram and Design – Library
• Suppose we are given the following text description of a system that we are being asked to design
and build:
• The library reading program software will allow librarians to create accounts for readers. An
account should be uniquely linked to an individual reader. An account includes unique reader
information, the number of minutes logged, and a reading passport. Reading passports
include stamps. Librarians set the number of minutes needed to earn a passport stamp.
Readers can log minutes, review their reading statistics, and look at the pages of their reading
passport. A reader can also request a new passport stamp. If the reader has enough minutes,
the stamp request will be granted. When a reader has a granted passport stamp request, a
new stamp slot appears in their passport and they can choose from the stamps available in the
system. The chosen stamp will be added to their passport.

• Object-oriented systems are composed of objects collaborating through messages to accomplish


work. The process of designing an object-oriented system requires first looking at the software
requirements with the purpose of finding objects and their relationships.
2.3 UML Diagrams in Design
Example: Sequence diagram and Design – Library

• We would first follow a requirements modeling process


(functional model), which begins with identifying the
actors that interact with the system. One purpose of
identifying the actors is to identify the boundaries of the
system – actors are outside the system we are building.
The second purpose is to identify use cases.
• In our description of the library reading program
software, two different kinds of users are named:
librarians and readers.
• The second step in the requirements modeling process
would be to list the system behaviors that each actor
will require to accomplish work.
2.3 UML Diagrams in Design
Example: Sequence diagram and Design – Library

• We will further specify each use case (when it starts, the flow of events, and when it ends). We will
also include variations on each use case that represent exceptions.
• To illustrate, we can write a description for the Reader use case Request passport stamp:

• Main flow of events: The use case starts when the Reader chooses to
request a passport stamp. The system will compare the Reader’s
unspent minutes to the number of minutes needed to earn a passport
stamp and add an empty stamp slot to the Reader’s passport. The
number of minutes spent on the stamp are deducted from the
Reader’s account, ending the use case.

• Exceptional flow of events: The Reader does not have enough


minutes to earn a passport stamp. The minutes in the Reader’s
account and the passport are unchanged. The system indicates the
Reader does not have enough minutes.
2.3 UML Diagrams in Design
Example: Sequence diagram and Design – Library

• We can then begin modeling and designing the system:

ü We can think of the system design as a set of collaborations, where a


collaboration is a set of classes that work together to realize a use case. This is a
dynamic view of the system, showing which objects are involved in fulfilling an
actor’s interaction with the system.

ü We will also create static system views composed of class diagrams, which show
the responsibilities of each class within the system. One class might have
responsibilities related to many collaborations. In other words, one class might
have responsibilities related to fulfilling many use cases.
2.3 UML Diagrams in Design
• We will use the Request passport stamp use case as an example:
ü In the Request passport stamp use case, a Reader (an actor outside) chooses to request a passport stamp,
and the system compares the Reader’s unspent minutes (minutes that have not already been awarded a
passport stamp) with the amount needed to earn a stamp. If the Reader has enough minutes, the minutes
will be deducted from their account and an empty stamp slot will be added to their passport. If the Reader
does not have enough minutes, the system will inform them and no changes will be made.

• We can identify the following system responsibilities in this use case:


ü providing the option to request a passport stamp,
ü maintaining the Reader’s unspent minutes,
ü maintaining the passport,
ü knowing the number of minutes required for a stamp,
ü deducting minutes from the Reader account,
ü adding a stamp slot to a passport,
ü and displaying a rejection message.
• To design an object-oriented system, we will then distribute the responsibilities among collaborating
objects. Each use case will contain a set of system responsibilities, so we can examine each use case
and propose object candidates (that will collaborate to fulfill the use case).
2.3 UML Diagrams in Design
Example: Sequence diagram and Design – Library

• Finding objects and classes, requires both invention and discovery. To discover objects within the
responsibilities, we should look for things. You can start with nouns in a description, but do not
limit yourself to nouns or expect that all nouns will be objects. Objects might be, for example,
concepts, organizations, events, algorithms, or interactions. We might also invent objects to
manage an interaction between other objects or facilitate some other collaboration within the
system.

• We will assess objects in our modeling according to other principles, such as whether they are a
natural part of the design or a collaboration mechanism, whether the same pattern of
collaborating objects has been used successfully to solve problems like the problem you are
solving, whether each object has a coherent set of responsibilities (high-cohesion), and whether
the objects are loosely coupled, meaning they are as independent as possible from the rest of the
system.
2.3 UML Diagrams in Design
Example: Sequence diagram and Design – Library

• In our use case, Request passport stamp, we can see what objects we can discover and invent.
• If we read the use case and responsibilities we found in the use case, we find some candidates: a
reader account, a passport, and a stamp. These are “things” in our list of system responsibilities.
If they are things which aggregate data and have a coherent set of responsibilities related to that
data, then they may end up as objects in our system.
• There are also several responsibilities related to the user-computer interface, such as giving the
Reader the choice to request a stamp, displaying an empty stamp slot in the passport, and
providing information that informs the Reader if the stamp request was rejected. It is practical to
separate the interface from the core part of our system that models the library reading program,
so we will factor out interface responsibilities from our discussion here.
• We have discovered several candidate objects from the Request passport stamp use case: reader
account, passport, and a stamp.
2.3 UML Diagrams in Design
Example: Sequence diagram and Design – Library

• We assign to the ReaderAccount object the name and uniquely identifying information for a
Reader, as well as the free minutes (minutes that have not been spent on a passport stamp), and
a passport. The ReaderAccount object allows the Reader to log minutes and request a stamp.
• This data and these responsibilities all relate to the reader account, so encapsulating this data
and these responsibilities together gives us a coherent object.
• The Passport object contains a list of stamps and can process stamp requests and allow the
Reader to choose a stamp. This is also an encapsulation of data and responsibilities that relate to
one “thing” from our requirements (the Passport object).
• The Stamp object will contain some data (such as text or an image, depending on whether we
have a graphical or text interface), and a minute value (the “cost” of the stamp). The Stamp
object will be able to display itself.
2.3 UML Diagrams in Design
Example: Sequence diagram and Design – Library

• We can draw a class diagrams for the ReaderAccount, Passport, and Stamp classes
with the responsibilities and data that we have assigned so far:
2.3 UML Diagrams in Design
• The next class diagram figure below shows the associations between these classes.
ü The Passport class has a composition association with the ReaderAccount class, because there should be one
passport for each Reader. A ReaderAccount has one Passport that is created when the ReaderAccount is
created, and the ReaderAccount destroys the Passport when the ReaderAccount is destroyed. Because the
Passport object is created with the ReaderAccount and is destroyed with the ReaderAccount, it is part of the
ReaderAccount.
ü The Passport object contains a list of Stamp objects. The list will be empty before the Reader logs minutes and
requests a stamp, so the cardinality of the Stamp objects is zero to many. Because there will be potentially
many ReaderAccount objects and therefore Passport objects, but a Stamp will not necessarily be contained in
any Passport lists, the cardinality of the Passport objects is also zero to many.
ü A Stamp object does not have a composition relation with a Passport object, as a Stamp object might be
displayed in many Passport objects (and therefore does not belong to, or live and die with, any one Passport
object). Therefore, the association between Passport and Stamp is a single-direction navigation association.
2.3 UML Diagrams in Design
Example: Sequence diagram and Design – Library

• The UML diagrams that we have looked at for our case study thus far are structural diagrams.
• They do not show the dynamic behavior of the system being developed. In other words, they do
not show how work is accomplished. A dynamic view or model will show the way that objects
collaborate to complete the tasks.
• A sequence diagram will show the objects that are collaborating to fulfill a use case by showing the
time ordering of the messages they send.
• We do not yet know what messages our objects will send to fulfill the Request passport stamp use
case. Drawing a sequence diagram will allow us to propose a candidate sequence of messages. We
can then use the full set of sequence diagrams to refine our class designs.

• The next chart is a proposed sequence diagram for the Request passport stamp task or use case.
2.3 UML Diagrams in Design
Example: Sequence diagram and Design – Library

• The next chart is a proposed sequence diagram for the Request passport stamp task or use case.

• Let’s discuss it in more detail on the next slides.


2.3 UML Diagrams in Design
• A sequence diagram shows the messages that objects send, to fulfill a use case. You can see the objects listed across
the top of the diagram, in boxes.
• Each object has a lifeline (a vertical dashed line from the box of the object’s name to the bottom). The lifeline
represents the object’s life over time. In this diagram, the reader and passport objects exist for the entire sequence.
• Messages are shown as arrows between the objects’ lifelines, pointing from the sender to the receiver. The name of
the message and parameters adorn the message arrow. When a value is returned from a method, that is shown as a
dashed line returning from the receiver back to the sender (with the name of the value being returned). When a
message is sent, we see an activation box on the lifeline indicating that the method has control.
• Time is represented in the diagram as proceeding from the top of the diagram to the bottom. The message at the top
of the diagram is the first message in the sequence diagram and begins the fulfillment of the use case. The last
message is the message at the bottom of the diagram.

• Generally, the object that begins the use case is on the left side
of the diagram, with the objects most involved in the use case
to the left side and less important objects to the right.
2.3 UML Diagrams in Design
ü The next Request passport stamp use case begins when the
ReaderAccount object sends a request_stamp message to
the Passport object.
ü The ReaderAccount passes itself as a parameter, so the
Passport object can send messages back to the
ReaderAccount as needed.
ü You can see, by the activation box on its lifeline, that the
Passport object has control for the rest of the diagram as it
handles the request_stamp message.
ü The first message it sends is the get_free_minutes message
to the Passport object. The Passport object responds to the
message by returning the number of free minutes it is
storing. The Passport object will then determine if the
ReaderAccount has accumulated enough free minutes to
earn a stamp. This logic, as it does not require any message
sends, is not shown in the diagram. The Passport object will
also add an empty stamp slot to itself, which, at this time,
also does not require message sends.
2.3 UML Diagrams in Design
ü The Passport object will send a deduct_free_minutes
message to the ReaderAccount object with the number of
minutes to deduct as a parameter. The Passport object is
responsible for knowing how many minutes each stamp
costs, and so this number will be the same or smaller than
the free_minutes value returned by the ReaderAccount in
response to the get_free_minutes message.
ü The ReaderAccount object will deduct the minutes from its
total free minutes. Again, because this operation does not
require a message send, it is not shown here.
ü Finally, the Passport object will complete processing the
request_stamp method by returning a status value. For the
sequence diagram shown, this will be a success value, as this
sequence diagram shows the messages that are sent if the
ReaderAccount has enough minutes to earn a stamp. If the
ReaderAccount did not have enough minutes, the Passport
object would not send the deduct_free_minutes message
and would return a failure status.
2.3 UML Diagrams in Design
ü While designing, we might realize that the Stamp objects would benefit from a manager object, a single object
responsible for creating and maintaining the list of all Stamp objects.
ü There is no StampManager in our description, but some system responsibilities do not seem to belong in any other
object in our system, such as displaying the list of available stamps when the Reader chooses a stamp. There is a need
for some organization of the Stamps beyond a simple list, so we invent the StampManager object.

ü Another responsibility the StampManager


will have is to know the cost of a stamp,
and another will be to maintain a special
instance of a Stamp object to represent an
empty slot in the reader’s passport. The
single empty stamp instance will be special
because it can be replaced by another
stamp of the same value.
ü We can then update our sequence diagram
for the Request passport stamp use case
that includes the StampManager object
2.3 UML Diagrams in Design
ü In the new sequence diagram, you can see the addition
of the StampManager object on the right.
ü The Passport object asks the StampManager object for
the cost of a stamp, so the Passport object can compare
the cost to the number of free minutes the
ReaderAccount has available.
ü The Passport object also asks the StampManager for
the empty stamp (the stamp that indicates an open
stamp slot in the Reader’s passport), and the
StampManager will return the empty stamp from that
method.
ü This message and the deduct_free_minutes message
are now enclosed in an alt block, which is a conditional
block. The alt block is a box marked “alt” that encloses
the conditional messages. Below the alt box is the
condition under which the messages will be sent, which
is free_minutes >= stamp cost, meaning the
ReaderAccount has enough free minutes for a stamp.
2.3 UML Diagrams in Design
• You can read this diagram two ways:
ü read all the messages, from top to bottom, to see the messages that are sent when the
ReaderAccount has enough free minutes to earn a stamp.
ü If the ReaderAccount does not have enough free minutes, read the messages from top to
bottom, but skip over the messages enclosed in the alt box, as they will not be sent if the alt
condition is false.
2.3 UML Diagrams in Design
• Let’s see an implementation of the Stamp class:
• A Stamp object has two fields:
ü a value (for our purposes here, a text name for
the Stamp object)
ü and a cost (the Stamp object’s cost in minutes)
• And there is one accessor method for each field, plus
a __str__ method. Notice that we are here using a
string as a Stamp object’s representation (we can
imagine that if we designed a graphical interface, a
Stamp would be represented by an image).
• We give the stamp the _cost field in anticipation of a
version of the program in which there could be
stamps awarded for different amounts of minutes, so
that Readers could choose a low-cost stamp or save
up for a higher cost stamp.
2.3 UML Diagrams in Design
• The StampManager class is the class we invented
to manage the collection of Stamp objects.
• Our program will have one set of Stamp objects,
including the “empty stamp,” an stamp that shows
an empty slot in a Passport object and can be
replaced by another stamp of the same value.
• Managing the Stamp objects includes ensuring that
there is only one copy of each Stamp object,
managing the empty stamp, managing the cost of a
stamp, and managing the display and choosing of a
Stamp object.
• The last responsibility is not included here, as it is
not needed for the Process stamp request use case.
However, if we continued to develop this system,
we would add that functionality to the
StampManager class.
2.3 UML Diagrams in Design
• When a class-level field is referenced within the class
definition but outside of a method (as it is here) we
do not prepend the field name with the class name
(we do not prepend the field name with
StampManager, in this example). That is because a
class definition has its own scope, like a function or
method, so the class-level variables are like local
variables in the class-level scope and we refer to
them by their names only.
• We have two accessors in the StampManager class:
ü one for the stamp cost
ü and one for the empty stamp.
• We use the class name to reference the fields
(StampManager._stamp_cost and
StampManager._empty_stamp). These are the
methods needed to do the stamp request use case.
2.3 UML Diagrams in Design
• Much of the work of fulfilling the Process
stamp request use case is done in the Passport
object’s request_stamp method.
• A Passport object has a list of Stamp objects,
initialized to the empty list, and a reference to
the StampManager object.
• There is also a __str__ method (string
representation of the object) to facilitate
testing (we will see more in the main() code).
• The request_stamp method takes the
requesting ReaderAccount as a parameter.
2.3 UML Diagrams in Design
• The request_stamp method takes the requesting
ReaderAccount as a parameter.
• Within the method, the Passport object first sends a
message to the StampManager, get_stamp_cost, and
then to the ReaderAccount, get_free_minutes.
• It compares the values returned by these methods, and
if the free minutes are enough to earn a stamp.
• It proceeds with the conditional code: getting the
empty stamp from the StampManager, adding it at the
beginning of the list of stamps (so the Reader will see
their newest stamps at the front of the passport), and
sending the deduct_free_minutes message to the
ReaderAccount object with the cost of the stamp.
• Finally, it sets the flag success to True, and the method
returns the success flag.
2.3 UML Diagrams in Design
• The ReaderAccount class is responsible for managing
the data related to a Reader’s account

• It includes the Reader’s name, uniquely identifying


information, passport, and the number of minutes
read.

• In the initializer for the class, the _name and


_reader_id fields are initialized from parameters. The
number of free minutes is initialized to zero. You may
recall that a ReaderAccount has a composition
association with a Passport, and so a unique Passport
object is created in the initializer.
2.3 UML Diagrams in Design
• You can recognize two methods from our sequence diagram
and from the request_stamp method in the Passport class:
ü get_free_minutes
ü and deduct_minutes.

• These methods access and mutate the ReaderAccount


object’s free minutes data, respectively.

• The request_stamp method invokes the Passport object’s


request_stamp method.

• There is also a __str__ method and a log_minutes method,


which we can use in our testing function to examine the state
of the ReaderAccount object after we have logged minutes
and requested stamps, to ensure that the state of the system
meets our expectations.
2.3 UML Diagrams in Design
• The main testing function is used to demonstrate that
the Request passport stamp use case is implemented
according to specifications.

• This testing function is not a thorough test of the


system, but rather demonstrates that a
ReaderAccount with enough free minutes requesting
a stamp will be granted a stamp and will have the
stamp cost deducted from free minutes, and a
ReaderAccount without enough free minutes
requesting a stamp will not be granted a stamp and
will have no minutes deducted.
2.3 UML Diagrams in Design
• The function begins by creating the StampManager object
and two accounts.
• The StampManager object has a stamp cost of 90 minutes.
• The main function then logs 60 minutes for the first reader
account – not enough to earn a stamp – and requests a
stamp.
• The reader account is printed before the stamp request, the
success of the stamp request is printed (the value is False),
and the reader account is printed after the stamp request.
• The function then logs 90 minutes with the second reader
account and requests a stamp. Once again, the reader
account is printed before and after the stamp request and
the success of the stamp request is printed.
2.3 UML Diagrams in Design
• The function finally logs another 60 minutes for the
first reader account. If all is working correctly, the first
reader should now have 120 minutes.
• The function requests a stamp for the first reader and
prints the reader account before and after the request
and prints the success of the stamp request.
2.3 UML Diagrams in Design
Example: Sequence diagram and Design – Library

• The output of the execution shows that the ReaderAccount object does not change after an
unsuccessful stamp request – its minutes and Passport object remain in the same state as before
the call.

• A ReaderAccount object with the exact number of minutes needed for a stamp has the minutes
reduced to zero and the stamp added to the Passport object, and a ReaderAccount object with
more minutes than are needed has the minutes reduced by the cost of a stamp and a stamp
added to the Passport object.

• The design of the system that fulfills the Request passport stamp use case uses encapsulation
to separate the responsibilities and data of the system into objects
2.3 UML Diagrams in Design
Example: Sequence diagram and Design – Library
• The design of the system that fulfills the Request passport stamp use case uses encapsulation to
separate the responsibilities and data of the system into object:
ü Each object represents either a “thing” from the original design or an invention with a
coherent set of responsibilities and data that facilitates fulfillment of the use case.
ü Well-designed encapsulated objects have the following advantages: Objects facilitate
information hiding, or restricting access to implementation details that are likely to change
as the system is developed and maintained.
ü Each object has an interface, or set of public attributes (usually methods), that other objects
in the system can use to interact with it. The implementation details of how information is
represented and how methods work is private to the object.
ü This way changes can be made to the object’s implementation without affecting other parts
of the system. If object data is private and the methods are carefully designed, then the
only way the data can be changed is in well-defined ways. It is less likely that data will
become corrupted if access to it must come through the object’s interface.
2.3 UML Diagrams in Design
Example: Sequence diagram and Design – Library
• The design of the system that fulfills the Request passport stamp use case uses encapsulation to
separate the responsibilities and data of the system into object:

ü Some well-designed objects can be reused in other systems, just as well-designed functions
can be reused. Objects can sometimes be replaced with other objects with similar
functionality.
ü For example, we might design our reading program software to allow an individual library to
use a passport stamp reward or a different sort of reward, such as an animated sticker book
to which the Reader can add characters and items.
ü If we design the system to be general enough (for example, if we use the language “request
reward” rather than “request stamp”), then we could allow individual libraries to select
whatever reward system they want. In the implementation, we would “plug in” the reward
object corresponding to the reward selected by the library.
2.3 UML Diagrams in Design
• These benefits do not come automatically with object-oriented design. They must be considered
and built in as the system is being designed.
• For example, it is difficult to design a reusable or replaceable component if the component is not
loosely coupled to the rest of the system – in other words, as independent as possible.
• Objects’ responsibilities should relate to their data, and they should protect the data from
manipulation that is not prescribed by the design of a use case.
• For example, the ReaderAccount allows the free minutes to be logged and a value to be deducted
from free minutes, but it does not allow the number of free minutes to be arbitrarily changed.
• Finally, if interfaces are carefully designed to provide the necessary functionality without relying on
a specific implementation, objects can be modified without requiring changes in the rest of the
system (If we decide that stamps should have a Surface image as part of their data, or that the
StampManager will store stamps in multiple lists by value, we do not need to make any changes to
the other objects in the Request passport stamp use case).
• Changes will be localized to the affected objects. Good object-oriented design can help us write
resilient, reusable programs.
2.3 UML Diagrams in Design
• You can learn more about Python implementation of UML models

https://youtu.be/k58R_CsvVoE?si=MPOQSb34MzXVu65m
2.3 UML Diagrams in Design
• You can learn more about Python implementation of UML Sequence diagrams

https://youtu.be/TpxuwZBVF2s?si=7TTzULkELXqOOVr5

You might also like