You are on page 1of 83

Software Engineering

Bachelor of Computer Sciences


Carolina Bonnin - cbonnin@uda.ad
Overview
What you will learn

1. Introduction
2. Object Oriented Fundamentals
3. O.O Analysis: Dynamic Model
4. O.O Analysis: Static Model
5. Object Oriented Design
Object Oriented Design
1. Object Oriented Design
2. OO Design - Static Model
3. OO Design - Dynamic Model
4. State Transition Diagram
5. Design Principles
6. Design Patterns
1. OBJECT ORIENTED DESIGN
Introduction
• Design is the bridge between the analysis and implementation of the
software system
• During this phase, we must:
• Assign responsibilities to the system objects
• Normalize our diagrams
• Add additional information to them before proceeding with
implementation

Planning Analysis Design Development Testing Deployment Maintenance


Working on reusable design
• Apply design principles and design patterns will help us to obtain more exible code,
encouraging reusability.
• Development and maintenance time will be reduced and we will work on better and
ef cient solutions.
• We can reuse code by:
• Creating classes for creating graphic objects, data structures or inheritance relations
• Creating components (set of classes that collaborate to perform a task) that other
projects may use, only knowing its interface

Planning Analysis Design Development Testing Deployment Maintenance


fi
fl
Object Oriented Design
• Now, nally, we will introduce technological dependencies
on our choices.
Software
• What resources do we need to consider? Design
• Database system used (Relational DB, DBOO…)

• System requirements in terms of graphical interface

• Language used and its restrictions


Design Phase
• Non-functional requirements are also considered on this
stage

• Economic, legal and properties that need to be


achieved
Software
• Design phaase have two distinct parts: Software Design Architecture
and Software Architecture
fi
Software Architecture
• Architecture is about breaking large systems into sub- Presentation
systems: layer
• Independent

• Integrated with other components

• Created separately
Business
• Focus on quality: looking to ensure reliability, performance,
Logic layer
ef ciency and reusability at architectural level

• Many categories and types of architectures patterns:

• Landscape patterns: how components communicate


between them (service-oriented, microservices…)
Data Access
• Application patterns: how components are built layer
• We’re going to see architecture in 3 layers
fi
Software Architecture

Presentation • Responsible of the user interface. It obtains data from the business logic layer and it displays it.
layer

Business • Responsible of business logic, system features. It get data and sends it, after treating it, to the
Logic layer presentation layer.

Data Access • Stores and retrieve persistent data, sends it to the business logic layer
layer
Software Architecture

Presentation layer Business Logic layer Data Access layer


Design Criteria
• We can apply design principles that will help us to
work on strengths and weaknesses of our design.
• You already know some of them: abstraction,
encapsulation…
• Some new one:
• Coupling and cohesion
• Coupling: measures the dependency
between to related systems. A good design
is one that has a low level of coupling.
• Cohesion: measures the link between
elements that conform a class. High level of
cohesion is a good sign in terms of design.
2. OO DESIGN - STATIC MODEL
Implementation model
• The implementation model is a representation of a software system that is used to guide its
construction.
• It provides a detailed and concrete view of the system design, including:
• Architecture, components, and implementation details such as programming languages,
frameworks, and technologies
• We will consider that the implementation model will contain:
• The normalized conceptual model, describing the software classes and their relationships.
• Operation contracts, detailing what software class methods must do and updated
considering the previous normalisation.
• Sequence diagrams, showing the responsibilities and collaborations between software
classes when an operation is invoked.
Implementation model
• For technological reasons, the conceptual model obtained in the speci cation
stage needs to be transformed
• This transformation process is what we know as normalisation:
• The process of organising the data in a database or a class diagram to
minimise data redundancy and improve data integrity.
• Usually involves breaking down a complex classes into smaller, more
specialised classes based on their responsibilities and attributes.
• In the process of normalisation, derived attributes or operations can be
computed dynamically by the class or by other related classes, rather than
being represented as separate attributes or operations in the class.

fi
Implementation model
• The class diagram is modi ed to and we:
• Remove associations involving more than two classes
• Remove associative classes
• We decide how to process the derived information
• The integrity of the conceptual data model and the operation contracts
needs to be, both of them, normalized.
fi
Implementation model
Implementation model
Derived information
• After leading with associations involving more than two classes we need to see how we deal with derived
information.
• Derived information refers to the data or attributes that can be calculated or derived based on other attributes or
operations of the class.
• Derived information can be computed dynamically or statically by the class
• Example:
• "Rectangle" class has attributes for its "width" and “height", meaning that "area" attribute is made of
derived information
• Another example of derived information could be a "Person" class that has attributes for "date of birth"
and "current date". The "age" attribute of the person can be calculated as a derived information based on
the difference between the "date of birth" and "current date”
• Derived information is usually represented in a class diagram as a derived attribute or operation, with a slash ("/")
preceding its name to indicate that it is not a physical attribute but is instead calculated based on other attributes or
operations.
Derived information
• Dealing with this derived information while normalising, means:
• We delete the “/“ from the class diagram.
• We have two options to deal with this “/“ removed:
• We review the operation contracts responsible for calculating and
recording this values
• We add methods that calculate the value inside the classes
Derived information
Derived information

No condition referring /issuedBy

In this case, operation contract responsible of creating and invoice (issuedBy) and the one closing the rental (price) will have to be updated.
3. OO DESIGN - DYNAMIC
MODEL
Operation Contracts Normalisation
• Once we have detected all the things that needs to be normalized in the
class diagram we have:
• All associations are binary. Classes and multiplicity have been added/
modi ed but the meaning is the same.
• Updated or removed integrity restrictions
• Decided how to handle derived information
• Now we need to update the contracts!
fi
Operation Contracts Normalization

• Basically, we add more detail in terms of related objects and when the
operations will be valid or not, taking into account the new relations we
created in the class diagram.
Operation Contracts Normalization

Not normalized

Normalized
Operation Contracts Normalisation
• Basically, when the operation contracts have been normalised:
• We assign responsibilities to classes (when normalising the class
diagram, we create new classes and operations)
• We establish new collaborations between classes (we establish
navigability after normalising and we can design a system sequence
diagram)
Type of classes
• From all this classes that may appear after normalising we Presentation
can nd different ones: layer
• Boundary classes: required by the user interface
design (screen containing graphic objects, menus…)
• In the presentation layer
• Control classes: controlling different operations Business
Logic layer
• Bridge between presentation and business logic
layer
• Usually there’s a control class for each use case
• Entity classes: model real world entities, and the Data Access
objects created in this classes needs to be persistent layer
(they are the classes that appear on the normalized
conceptual diagram)
fi
Type of classes
• In order to represent all this classes and Presentation
layer
how they interact, we create sequence
diagrams:
• They explicitly identify the classes
Business
involved in each system operation, the
Logic layer
messages send between objects and
the order in which they are send.

Data Access
layer
UML - Sequence Diagram
• Two read directions:
• Horizontally: arrows indicate the direction of the message
• Vertically: chronological order of messages
UML - Sequence Diagram
• Constructor case:
• The object name is aligned with
the message that created it
• A constructor call always returns
the object instance
• If needed, we can explicitly
destroy an object
UML - Sequence Diagram
• Internal operation case:
• We can call inner object
methods
• Execution speci cation for this
new operation is overlaid to the
previous one
fi
UML - Sequence Diagram
• Opt / alt and loop cases:
• Opt: option. An if condition
without else.
• Alt: one or more alternate
conditions, if the rst is not true,
it jumps to the following one (if
else)
• Loop: block of messages that
gets passed as long as the
condition is true
fi
UML - Sequence Diagram
UML - Sequence Diagram
Class Design
• Attributes are private by default.
• Operations are public by default.
• Each class has a constructor with parameters for each one of the class
attributes.
• Each class have getter and setters.
• If the object have states, there must be an operation that can edit this state
(makeAvailable, pendingPayment, paymentDone…)
Class and methods syntax
• Visibility: public (+), private (-), protected (#)
• Multiplicity: univalued, multivalued, with null value
• [Visibility] name [Multiplicity] : type [=initialValue] [{constraints}]
• - country: String = “Principat d’Andorra”
• + addCountry(numPass:Integer, countryName:String): Boolean
• + medianAge(): Real
Materialising the associations
• We add, at the end of the association in the class diagram, the role in the
sense of navigation

• Each association has a creation operation and another to get the


association
4. STATE TRANSITION DIAGRAM
State Transition Diagram
• State transition diagram are an extension of a nite state machine
• The goal is to describe the dynamic behaviour of an entity
• It can describe any level of abstraction (system, component, object…)
• It uses:
• State of the entity
• Transition between states
• Events that trigger this transitions

fi
State Transition Diagram
• State: period of time during the life of an entity in which a set of
conditions are satis ed
• Transition: state change triggered by an event
• It’s a summary of the dynamics of the system
fi
State Types
• Initial state: system init, constructor
call…
• Final state: session ends, object
destroyed…
• Intermediate state: states of the
system, objects…
• Simple state: no internal transition
in this state
State Types
• Transition from initial state
indicates in which state the system
is initialised
• Many states can have transition to
the nal state
• The name of each state (inside
rectangles) must be unique
fi
State Types
• We can add state characteristics, explaining everything that needs to happen
to stay in the current state.
Event Types
• The expected events are all the events that may trigger a state transition
Event Types
• Events can be:
• Signal event: asynchronous message or signal
• Call event: calling an operation (for example the ones de ned in the class
diagram)
• Condition event: when (condition) —> condition is a Boolean expression that is
constantly evaluated until it’s true
• Time event:
• Relative date: after (Time)
• Absolute date: when (date=Date)

fi
Transition / Action
• The acton 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:
When do we use it
• 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
Example
5. DESIGN PRINCIPLES
Design principles
• Set of guidelines that help to improve the overall design
• Techniques that have been used with success in many object-oriented
designs
• By using them we avoid many common OO design mistakes resulting in
rigid, fragile and not reusable software
• The pillars for OOP are abstraction, encapsulation, inheritance and
polymorphism, as we’ve seen, but they are not enough to build high
quality software
• On top of this concepts, we apply design principles
GRASP principles
• First presented by Craig Larman’s
book: Applying UML and Patterns
• GRASP stands for:
• General Responsibility
Assignment Software Pattern
• Set of 9 design principles that help us
assigning responsibilities to classes
• We usually assign this responsibilities
during the creation of diagrams
GRASP principles
• Responsibility: obligation to perform a task or knowing an information.
• We can divide responsibilities in two types:
• Knowing responsibilities:
• Get private and public object data
• Get derived information
• Get object references
• Doing responsibilities:
• Do something: create an object, process data…
• Initiate and coordinate actions
GRASP principles
• GRAPS patterns:
• Information Expert
• Creator
• Low coupling
• High cohesion
• Controller
• Indirection
• Polymorphism
• Pure Fabrication
• Protected Variations
Information Expert
Problem: What is a basic principle by which to assign
responsibilities to objects?
Solution: Assign a responsibility to the class that has the
information needed to fulfil it

Given an operation that needs some


input data to be performed, assign
this responsibility to the class that
contains this data.
Information expert
• Given the following diagram, assign the responsibilities to obtain the sale
order total, and the total for all orders for each customer.
Information expert

• Assigning responsibilities requires collaboration between several partial


information.
• Each of the objects involved in the operation do their part, based on what they
know.
• All this responsibilities are assigned based on the information expert principle
Creator
Problem: Who creates object A?
Solution: Assign to class B the responsibility to create object A if
one of these is true (the more, the better):
- B contains or compositely aggregates A
- B records A
- B closely uses A
- B has the initialising data for A

• Creator is not only about having the data to create


the object, but also being closely related to it.
• Putting together two parts of code that are
semantically close, the creation of an object and the
usage of it results in increased clarity, encapsulation
and reusability
• A composite object is usually a good choice for
creating its parts
Creator

• Who should be responsible of creating SaleOrder?


• Customer aggregates SaleOrder, it has the initialisation data and closely
uses the SaleOrder. It’s an ideal candidate for “Order Creator”.
• May seem obvious but it’s worth to look at this when creating more
complex objects or arrays of objects.
Creator

• We usually take this decisions while drawing sequence diagrams


• We add the creator operation inside customer, and we do the same for
the SaleOrderLine creator, in this case, SaleOrder.
Low Coupling
Problem: How to reduce the impact of change? How to support low
dependency and increase reuse?
Solution: Assign responsibilities so that coupling remains low. Use this principle
to evaluate alternatives.

* Coupling: interdependence between different parts of a software system. A


high coupling level means that changes in one module or component are likely
to affect other parts of the system, making it harder to modify and maintain.

• The main goal is to assign dependencies that will reduce the


impact of changes.
• If we do not manage coupling we may end up with:
• No reusable design: classes have too many dependencies on
others
• Maintainability problems: we change something that breaks
everything
• High coupling = software dif cult to read and understand
fi
Low Coupling
• Types of coupling:
• A has an attribute type B
• A calls method B
• A has method that references B
• A is a direct or indirect subclass of B
• A implements the interface B
High cohesion
Problem: How to keep objects focused, understandable, meanageable and
as a side effect, support Low Coupling?
Solution: Assign responsibilities so that cohesion remains high. Use this
principle to evaluate alternatives.

* Cohesion: responsibilities and functions within a module are closely


related and serve a single purpose.

• Focus classes around one responsibility


• High cohesive classes allow better mental
abstraction as we can mentally label them
as “this class does X”, no “this class does
A, B, C and a little bit of X and Y”
High cohesion
Controller
Problem: What first object beyond the UI layer receives and coordinates a
system operation?
Solution: Assign the responsibility to an object representing one of these
choices:
- Represents the overall system or a major subsystem
- Represents a use case scenario within the system operation occurs

• Basically, answer the question: “Who should be


responsible of handling input system events?
• An object controller is created in order to
handle the system events. It’s the rst non-UI
component that receives system operations as
UI-events
fi
Controller
• The controller has to:
• Capture the input event
• Organise and coordinate the activity to react to this
event
• Input events include everything that may interact with
the UI (a person using the GUI, signal from a sensor,
call from an external system…)
• This responsibilities will be assigned to:
• One single object for the overall system (Façade
Controller
• One object for each use case, noted as:
UseCaseName + Handler|Coordinator|Session
Indirection
Problem: Where to assign a responsibility to avoid direct coupling between
two or more things?
Solution: Assign the responsibility to an intermediate object to mediate
between other components or services so they are not directly coupled.

• Indirection pattern is used to reduce coupling


between two classes A and B by creating an
intermediate class between them.
• Like this, changes between A and B will not affect each
other, the intermediate class will absorb the changes.
• Indirection supports low coupling but may reduce
readability.
Indirection
• Let’s avoid direct coupling between customer and saleOrder:
Pure Fabrication
Problem: What object should have the responsibility, when you do not want
to violate High Cohesion and Low Coupling, but solutions offered by other
principles are not appropriate?
Solution: Assign a highly cohesive set of responsibilities to an artificial or
convenience class that does not represent a problem domain concept.

• Sometimes there are responsibilities that


doesn’t t well any of our classes.
• Forcing this responsibility to an existing
cohesive class, it’s a bad idea.
• Pure fabrication suggests to create a new class
to achieve this new responsibility.
fi
Protected Variations
Problem: How to design objects, subsystems and systems so that the
variations or instability in these elements does not have an undesirable
impact on other elements?
Solution: Identify points of predicted variation or instability, assign
responsibilities to create a stable interface around them.

• We need to avoid changes in A that will affect B.


So, we protect B from A variations.
• To achieve that, we organise responsibilities
around well de ned and organised interfaces.
• This principle is particularly relevant for the parts of
the code that tends to change often.
• Introducing interfaces between this code and the
rest of the system helps to prevent problems.
fi
Polymorphism
Problem: How handle alternatives based on type?
Solution: When related alternatives or behaviours vary by type (class),
assign responsibility for the behaviour (using polymorphism operations) to
the types for which the behaviour varies.

• We can see polymorphism as having a base


class with virtual methods that de nes an
interface and derived classes that
implements it.
• We will use polymorphism when there are
several ways to perform an action, and we
want to decouple this several ways to do it.
fi
6. DESIGN PATTERNS
Design Patterns
• A design pattern is a general
solution to a problem that appears
several times in software
development
• Design patterns solve speci c
design problems in order to create
more exible, reusable and elegant
systems
• Design patterns are build on top of
design principles
fl
fi
Design Patterns
• Patterns are not restricted to any domain or
programming language.
• Each pattern describes a problem that is
repeated over and over, as well as the solution
• Patterns are methods, documented in a
catalog, that give us a systematic way to
approach problems:
• GRASP: patterns of basic design principles
• GOF: "Design patterns : Elements of
reusable object oriented software" Authors
Gamma, Helm, Johnson Vlissides are
informally known as Gang of Four.
Patterns classification (GoF)
• Creational patterns: about class instantiation or object creation
• Factory method, Abstract factory, Builder, Singleton…
• Structural patterns: about organising different classes and objects to form
larger structures
• Adapter, Bridge, Composite, Decorator, Façade, Proxy…
• Behavioural patterns: identifying common communication patterns
between objects
• Iterator, Mediator, Observer, State, Strategy…
Adapter Pattern
Problem: Reuse an existing class, but its interface
does not allow it

• The adapter pattern converts the interface


of a class into another interface that the
client wants
• Used to allow incompatible objects to
interact
Adapter Pattern
• Client wants to get a book to publish it in his website
• The client expects to call two methods:
• getName: returns book’s title
• getPrice: returns book’s price
• Our book class have this two methods:
• getName: returns book’s title
• getPriceInCents: return price in cents
Adapter Pattern
Adapter Pattern
• Target interface: the
interface the client will use
• Adaptee class: our current
class with a different
interface
• Adapter class: implements
the target interface by
reusing the existing
functionality in the adaptee
class
Iterator Pattern
Problem: Need to do a sequential tour of a
collection of objects

• Provides a way to access the elements of an


aggregate object without exposing the
implementation
• Mainly used when we want the same
interface to access elements in a collection
without knowing the underlaying
implementation
Simple Factory Pattern
Problem: Decoupling the process of creating
objects from the clients that use them

• A class will take the responsibility of


creating objects
Simple Factory Pattern
• Part of the code may change in the
future if we add new pizzas.
• We will create a simple factory
where all this code can be placed
Simple Factory Pattern
Strategy Pattern
Problem: Create a family of algorithms for a task and
being able to decide which one we chose at runtime.

• The algorithm will vary depending on the


client that uses it

You might also like