001 015 Merged
001 015 Merged
Fakhar Lodhi
Topics Covered: 001 – 015
Software Design Concepts
Software Design and Architecture
Topic#001
Design – What and Why
What is design?
Definition from Cambridge Dictionary
Verb
to make or draw plans for
something, for example clothes
or buildings
What is design?
Definition from Cambridge Dictionary
Noun
a drawing or set of drawings
showing how a building or
product is to be made and how it
will work and look
Dress Design
Product Design
Mechanical Design
Building Elevation
Design
Building Floor Plan Design
Landscape Design
Interior Design
Software Design
Software Design
Software Design
Why should structures/systems
need to be designed at all?
"You can use an eraser
on the drafting table or a
sledgehammer on the
construction site.“
--Frank Lloyd Wright
Software Design and Architecture
Topic#001
END!
Software Design and Architecture
Topic#002
Design – Objectives
Software Design Objectives
The
A "blueprint"
System Software
for
Specification Design
implementation
Process
Software Design Objectives
The
A "blueprint"
System Software
for
Specification Design
implementation
Process
During the design phase, software engineers
apply their knowledge of:
• the problem domain
• implementation technologies
Software Design Objectives
The
A "blueprint"
System Software
for
Specification Design
implementation
Process
Should be “efficient”
Software Design Objectives
The
A "blueprint"
System Software
for
Specification Design
implementation
Process
Topic#002
END!
Software Design and Architecture
Topic#003
Software Design – Complexity
Poorly designed
programs are difficult
to understand and
modify
Cost of adding the ith feature to a well-designed and poorly designed program
Software Design and Architecture
Topic#003
END!
Software Design and Architecture
Topic#004
Software Design
Complexity and Size
The size
does
matter!
The larger the
program, the more
pronounced are the
consequences of
poor design
Software Design and Architecture
Topic#004
END!
Software Design and Architecture
Topic#005
Software Design
Types of Complexities
Two Types of Complexity in Software
Essential complexities –
complexities that are
inherent in the problem.
Two Types of Complexity in Software
Accidental/incidental
complexities –
complexities that are artifacts
of the solution.
Two Types of Complexity in Software
Topic#005
END!
Software Design and Architecture
Topic#006
Why is Software Design Hard?
Why Design is Hard
Design is difficult because
design is an abstraction of
the solution which has yet
to be created
Software Design and Architecture
Topic#006
END!
Software Design and Architecture
Topic#007
Software Design
A science or an art?
Difficulty with design
Design A Science
An Art
Software Design and Architecture
Topic#007
END!
Software Design and Architecture
Topic#008
Software Design
A Wicked Problem
A wicked problem
A problem that can only be
clearly defined by solving it
Topic#008
END!
Software Design and Architecture
Topic#009
How to make the design process
more systematic and
predictable?
The design process can be
made more systematic and
predictable through the
application of methods,
techniques and patterns, all
applied according to principles
and heuristics.
Software Design and Architecture
Toipc#009
END!
Software Design and Architecture
Topic#010
Role of Modularity, Hierarchical
Organization, Information Hiding, and
Abstraction in dealing with software
complexity
Good design doesn’t reduce the
total amount of essential
complexity in a solution but it
will reduce the amount of
complexity that a programmer
has to deal with at any one time
A good design will manage
essential complexities
inherent in the problem
without adding to accidental
complexities consequential to
the solution.
Modularity
subdivide the solution into
smaller easier to manage
components
Topic#010
END!
Software Design and Architecture
Topic#011
Characteristics of Software
Design
A deterministic process is
one that produces the same
output given the same
inputs
Design A Science
An Art
Design is non-deterministic
Topic#011
END!
Software Design and Architecture
Topic#012
Benefits of Good Design
Good design reduces
software complexity - making
the software easier to
understand and modify
Rapid development
Easier Maintenance
Good design makes it easier
to reuse code.
• It improves software quality.
Topic#012
END!
Software Design and Architecture
Topic#013
A Generic Design Process
The final design evolves from
experience and feedback
Topic#013
END!
Software Design and Architecture
Topic#014
Inputs to the design process
User requirements and
system specification
(including any constraints
on design and
implementation options)
Domain knowledge (For
example, if it’s a healthcare
application the designer
will need some knowledge
of healthcare terms and
concepts.)
Implementation knowledge
(capabilities and limitations
of eventual execution
environment)
Software Design and Architecture
Topic#014
END!
Software Design and Architecture
Topic#015
Desirable Internal Design
Characteristics
Poorly designed programs
are difficult to understand
and modify
Ease of maintenance – Your
code will be read more often
then it is written.
Desirable Internal
Design Characteristics
Minimal complexity
Keep it simple
Topic#015
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 016 – 020
Desirable Internal Design Characteristics
Software Design and Architecture
Topic#016
What is good design?
What is good design?
· Is it efficient code?
· compact implementation?
· Most maintainable?
Maintainable Design
· Cost of system changes is minimal
· Readily adaptable to modify existing functionality and
enhance functionality
· Design is understandable
· Changes should be local in effect
Topic#016
END!
Software Design and Architecture
Topic#017
Coupling
Coupling
· Coupling is the measure of dependency between
modules/components.
· The degree of interdependence between two
modules/components
· A dependency exists between two
modules/components if a change in one could
require a change in the other.
Inter-component relationship
Measuring Coupling
· The degree of coupling between modules is
determined by:
· The number of interfaces between modules (quantity)
· Complexity of each interface (determined by the type of
communication) (quality)
Why is high degree of coupling
bad?
· Highly coupled systems have strong interconnection
· High dependence of program units upon one another
· Difficult to test, reuse, and understand separately
Topic#017
END!
Software Design and Architecture
Topic#018
Coupling – Example
Design of a simple web app
<!doctype html>
<html>
<head>
<script type="text/javascript" src="base.js">
</script>
<link rel="stylesheet" href="default.css">
</head>
<body>
<button onclick="highlight2()">Highlight </button>
<button onclick="normal2()">Normal </button>
<h1 id="title" class="NormalClass">
CSS <--> JavaScript Coupling
</h1>
</body>
</html>
.NormalClass {
color:inherit;
font-style:normal;
}
default.css
<!doctype html>
<html>
<head>
<script type="text/javascript" src="base.js">
</script>
<link rel="stylesheet" href="default.css">
</head>
<body>
<button onclick="highlight2()">Highlight </button>
<button onclick="normal2()">Normal </button>
<h1 id="title" class="NormalClass">
CSS <--> JavaScript Coupling
</h1>
</body> We want to change the style of the title in
</html>
response to user action
function highlight() {
document.getElementById("title").
style.color="red";
document.getElementById("title").
style.fontStyle="italic";
}
function normal() {
document.getElementById("title").
style.color="inherit";
document.getElementById("title").
style.fontStyle="normal";
}
Option A
JavaScript code modifies the style attribute of HTML element.
function highlight() {
document.getElementById("title").
className = "HighlightClass";
}
function normal() {
document.getElementById("title").
className = "NormalClass";
}
Option B
JavaScript code modifies the class attribute of HTML element.
.NormalClass {
color:inherit;
font-style:normal;
}
.HighlightClass {
color:red;
font-style:italic;
}
default.css
Software Design and Architecture
Topic#018
END!
Software Design and Architecture
Topic#019
Cohesion
Cohesion
· Cohesion refers to the degree to which the
elements inside a module belong together
· A measure of the strength of relationship between:
· the methods and data of a class and some unifying
purpose or concept served by that class
· the class’s methods and data themselves
Topic#019
END!
Software Design and Architecture
Topic#020
Relationship between Coupling
and Cohesion
High Cohesion and Low Coupling - Benefits
Highly Cohesive Modules Lowly Coupled Modules
· easier to read and · easier to read and
understand understand
· Easier to modify · Easier to modify
· Increased potential for · Increased potential for
reuse reuse
· Easier to develop and test · Easier to develop and test
Surprised?
Are they somehow related?
Low Cohesion and High Coupling High Cohesion and Low Coupling
Cohesion and Coupling
· Coupling: Inter-component relationships
· Cohesion: Intra-component relationships
Topic#020
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 021 – 027
Object-Orientation – Introduction
Software Design and Architecture
Topic#021
Software Design Strategies
Structured and Object-Oriented
Design
Software Design Strategies
· Structured Design
· Object-Oriented Design
Structured Design
· System is designed from a functional view point
· Conceived as a set of functions that are used to solve the
problem at hand
· The system state is centralized and is shared among the
functions operating on that state
Structured Design
· What the set of
functions/programs should be?
· What each function should
accomplish?
· How functions should be
organized in a hierarchy?
· Start with a high level view and
progressively refine this into more
detailed design
Action-Oriented
Object-Oriented Design
· Based on the idea of information hiding
· System is viewed as a collection of objects
· The system intelligence and state is decentralized and
each object manages its own state information
· Attributes (state) and Operation (intelligence)
· Objects communicate by exchanging messages
Maintainable Design
What? How?
· Cost of system changes is · Low coupling and high
minimal cohesion
· Design is understandable · Self contained components
· Changes should be local in · Close relationship of data
effect and function
Object-Oriented Design
Software Design and Architecture
Topic#021
END!
Software Design and Architecture
Topic#022
Object-Orientation Basic Concepts
The Object and The Class
The Object
· An object is a tangible entity that exhibits some well
defined behavior.
· An object represents an individual, identifiable item, unit,
or entity, either real or abstract, with a well defined role
in the problem domain
Topic#022
END!
Software Design and Architecture
Topic#023
Object-Orientation Basic Concepts
The Class
The Class
· Represents similar objects
· Its instances
In object-oriented programming, a class is a blueprint for creating objects (a particular data structure), providing initial
values for state (member variables or attributes), and implementations of behavior (member functions or methods).
A class diagram is a graphical representation of a static structural model that displays unique architecture types of the
software components optionally with software methods and properties. Class diagrams capture one instance of each
referenced model and show relationships between them
Template of an object
Properties and Behavior
The Class
· A class represents an abstraction
· Specifies an interface ( the outside view - the public part)
· What can I do for you?
· declaration of all the operations applicable to instances of this class
· Defines an implementation (the inside view - the private part)
· How is it actually done?
· The structure – how the information is maintained
· The implementation of the operations declared in the interface
· How a task is performed – the algorithm
Software Design and Architecture
Topic#023
END!
Software Design and Architecture
Topic#024
Object-Orientation Basic Concepts
Relationship between Classes and
Objects - Association
Relationship between Classes
· Classes and Objects – two building blocks of the system
· Behavior of the system is defined by the manner in which
the objects interact with one another
· In order to construct a software system, we need
mechanisms that create connections between these
building blocks
· Association
· Inheritance
Association
· Indicates that the objects of the two classes are related in
some non-hierarchical way
· Implies that an object of one class is making use of an
object of another (or same) class
· Indicated simply by a solid line connecting the two class
icons.
Association
· Does Not imply that there is always a link between all
objects of one class and all objects of the other
· Does imply that there is a persistent, identifiable
connection between two classes.
Topic#024
END!
Software Design and Architecture
Topic#025
Object-Orientation Basic Concepts
Relationship between Classes and Objects
Aggregation and Composition
Aggregation
· A form of association that specifies a whole-part
relationship between an aggregate (a whole) and a
constituent part
· Indicated by a “hollow” diamond
A B
Aggregation
· Most experts have downplayed the importance of general
form of aggregation as not something that deserves to be
embellished in any way
A B
Software Design and Architecture
Topic#025
END!
Software Design and Architecture
Topic#026
Object-Orientation Basic Concepts
Relationship between Classes and Objects
Inheritance
Classification and Hierarchy
· Classification of objects into groups of related
abstractions
Inheritance
· Represents a hierarchy of abstraction in which one class
inherits from one or more super-classes.
· One class shares the structure or behavior defined in one
or more classes.
· A subclass augments or redefines the existing structure
and behavior of its super-class.
Generalization/Specialization hierarchy
Inheritance Hierarchy
· Show the relationships among superclasses and
subclasses
· A triangle shows a generalization
B C
Inheritance
· The implicit possession by all subclasses of features
defined in its superclasses
· The implicit possession by all subclasses of features
defined in its superclasses
Inheritance is the process by which genetic information is passed on from parent to child. This is why members of the
same family tend to have similar characteristics.
Topic#026
END!
Software Design and Architecture
Topic#027
Object-Orientation Basic Concepts
Abstract Classes and Interfaces
Abstract Class
· When we write a class, we code every field and method;
in other words, the code is complete in a sense
· Sometimes, we might know the specifications for a class,
but might not have the information needed to implement
the class completely
· In such cases, we can implement a class partially using
what are called abstract classes.
Abstract Class
· It provides a basic implementation that other classes can
inherit from
· An instance of the abstract class cannot be created
Interface
· A mechanism to achieve abstraction
· A collection of abstract methods
· No state or implementation
Interface vs Abstract Class
· Abstract classes can be inherited
· A class that implements an
without implementing the
interface must provide an
abstract methods (though such a
implementation of all the
derived class is abstract itself)
methods of that interface
· Abstract classes may contain
· Interfaces can have no state or
state (data members) and/or
implementation
implementation (methods)
Topic#027
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 028 – 047
Implementing Relationships
Software Design and Architecture
Topic#028
Relationships – Basic Concepts
Object Oriented Programming Defined
OOP as defined by Grady Booch
A method of implementation in which
programs are organized as cooperative
collections of objects, each of which
represents an instance of some class,
and whose classes are all members of a
hierarchy of classes united via
inheritance relationships.
3
Relationships
• Hierarchy of classes
• Inheritance - relationship among classes
Topic#028
END!
Software Design and Architecture
Topic#029
Relationships – Basic Concepts
Association
Association
An association is a
relationship among two or
more specified classifiers that
describes connections among
their instances.
Association
•Associations are the “glue” that
holds together a system.
•Uses Relationship
•Simple Association
•Whole-Part Relationship
•Aggregation
•Composition
UML Object Model Notation
super class
End - Association
Association
class name
attribute name
Class1 Class
Operation
Attribute1 Attribute: name
0..*
Operation1a Operation:
Operation1b
subclass
name
Multipicity of
association
Class5 Class2 Class3 Class4
1
Attribute5a Attribute2a Attribute3a 1+ Attribute4a
Attribute2b Attribute4b
Topic#029
END!
Software Design and Architecture
Topic#030
Relationships – Basic Concepts
Aggregation and Composition
Aggregation
A form of association that
specifies a whole-part
relationship between an
aggregate (a whole) and a
constituent part.
Aggregation
The distinction between
aggregation and association is
often a matter of taste rather
than a difference in semantics.
Think of it as a modeling placebo
Aggregation
“Aggregation is strictly
meaningless; as a result, I
recommend that you ignore it in
your own diagrams”
UML Distilled by Martin Fowler
Composition
A form of aggregation
association with strong
ownership and coincident
lifetime of parts by the whole
Composition
A form of aggregation
association with strong
ownership and coincident
lifetime of parts by the whole
End – Aggregation and Composition
Software Design and Architecture
Topic#030
END!
Software Design and Architecture
Topic#031
Object Lifetime and Visibility
Inheritance
Inheritance
•B inherits from A
•A is the super or base class
and B is the sub or derived
class
•A does not know about B
When an object of Type B is created,
a corresponding object of Type A is
also created
a5
a5 is only accessible from b2.
exclusive holding
The life of a5 is dependent
b2
upon b2.
a5 is created with b2 and it
dies with b2. a5
Cardinality of this relationship
is 1:1
End of topic
Software Design and Architecture
Topic#031
END!
Software Design and Architecture
Topic#032
Object Lifetime and Visibility
Composition
Composition
•Whole-part relationship
•B has many instances of A
•B is the container or
whole, A is the part.
•A does not know about B
Composition
•A form of aggregation association
with strong ownership and
coincident lifetime of parts by the
whole.
•A part may belong to only one
composite.
Composition
•Parts with non-fixed multiplicity may be
created after the composite itself.
•Once created, they live and die with it
(that is, they share lifetimes).
•Such parts can also be explicitly
removed before the death of the
composite.
Composition – object creation and life-time
When an object of Type B is created,
corresponding instances of Type A are
also created
Conceptually speaking, the object of b2
Type B holds the corresponding
objects of Type A as private a5 a6
components.
For example, when an object, say b2,
of Type B is created, some objects of
Type A, say a5 and a6, are also
created.
Composition – object creation and life-time
a5 and a6 are only accessible from
b2.
exclusive holding
The life of a5 and a6 is dependent b2
upon b2. a5 a6
a5 and a6 are created with b2
and destroyed with b2.
Cardinality of this relationship
could be 1:1 or 1:m End of topic
Software Design and Architecture
Topic#032
END!
Software Design and Architecture
Topic#033
Object Lifetime and Visibility
Association
Association – some
sort of link between
objects
•One instance of B is
associated with
many instances of A
Association – object creation and life-time
Objects of the two types
have independent life
times. b2
Conceptually speaking,
objects of Type B are
linked with objects of a5 a6
Type A.
Association – object creation and life-time
Therelationship is not b2
exclusive. That is, the
same instance of A may a5 a6
also be linked and
accessed directly by b3
other objects.
a7
Association – object creation and life-time
Cardinalityof this b2
relationship could be 1:1,
1:m, or m:m a5 a6
b3
End of topic a7
Software Design and Architecture
Topic#033
END!
Software Design and Architecture
Topic#034
Object to Relational Mapping
Basics
● Relational Database
● Objects
● Mapping between Objects & Relational
O2R Mapping MCQS
•Mapping attributes
•Mapping Inheritance
•Mapping Association
•Mapping Composition End of topic
40
Software Design and Architecture
Topic#034
END!
Software Design and Architecture
Topic#035
Object to Relational Mapping
Mapping Inheritance
Subjective + MCQ
Mapping Inheritance
A
• Filtered Mapping
id_a
• Horizontal Mapping a1
• Vertical Mapping
B C
id_b id_c
b1 c1
43
Filtered Mapping
TableName
•All the classes of an a_id
inheritance a1
hierarchy are b_id
b1
mapped to one c_id
table. c1
44
Horizontal Mapping
• Each concrete class is TableForB TableForC
mapped to a separate a_id a_id
table and each such a1 a1
table includes the b_id c_id
attributes and the b1 c1
inherited attributes of
the class that it is
representing.
End of topic
45
Software Design and Architecture
Topic#035
END!
Software Design and Architecture
Topic#036
Object to Relational Mapping
Mapping Inheritance – Vertical Mapping
IMP FOR SUBJECTIVE AND MCQ
Topic#036
END!
Software Design and Architecture
Topic#037
Object to Relational Mapping
Mapping Composition
each class of the whole-part hierarchy is
mapped to a separate table.
To maintain the whole-part relationshipbetween
the whole (composite class) and the part
(component class), primary key (OID) of the
composite class is inserted in the part classes as
a foreign key.
note the difference between composition and
inheritance
Composition – Persistence
- Example
Composition – Persistence - Example
oid_b u v oid_a oid_b(FK) x y
10 23 10 1 21 567 100
21 34 54 2 21 98 43
35 78 17 3 35 718 127
Topic#037
END!
Software Design and Architecture
Topic#038
Object to Relational Mapping
Mapping Association
Each class involved in the relationship
is mapped to a separate table.
To maintain the relationshipbetween
the classes, primary key (OID) of the
user class is inserted in the classes that
have been used as a foreign key.
Note that, in the OO world, the client knows
the identity of the server whereas in the
relational world, the table for server holds
the identity of the client.
For many-t-many relationship a separate
table is used to maintain the information
about the relationship.
Association – Persistence
Composition – Persistence - Example
oid_b u v oid_a oid_b(FK) x y
10 23 10 1 21 567 100
21 34 54 2 21 98 43
35 78 17 3 35 718 127
Topic#038
END!
Software Design and Architecture
Topic#039
Object to Relational Mapping
Mapping Cardinality of Association
One-to-One Relationships
1
Customer Address
1
Customer Table
Address Table
-CustomerOID (PK)
-AddressOID (PK)
-CustomerNumber
-House
-AddressOID (FK)
1 1 -Street
-Name
-City
-SSN
65
One-to-Many Relationships
1
Customer Invoice
*
End of topic 67
Software Design and Architecture
Topic#039
END!
Software Design and Architecture
Topic#040
Object to Relational Mapping
Summary
What Life-time Holding / visibility cardinality
Exclusive MCQS
Inheritance
Exclusive
Part is created and FOR MCQ
whole-part destroyed with the 1:1, 1:m
relationship whole Part does not know
about the whole
FOR MCQS
Association
Non-exclusive
Using relationship
independent 1:1, 1:m, m:m
link Can be one-way or
bi-directional
End of topic
Software Design and Architecture
Topic#040
END!
Software Design and Architecture
Topic#041
OOP – Inheritance and Polymorphism
class Polygon {
protected:
int width, height;
public:
Polygon (int a, int b) : width(a), height(b) {}
virtual int area (void) =0;
void printarea()
{ cout << this->area() << '\n'; }
}; 74
class Rectangle: public Polygon {
public:
Rectangle(int a,int b) : Polygon(a,b) {}
int area()
{ return width*height; }
};
75
class Triangle: public Polygon {
public:
Triangle(int a,int b) : Polygon(a,b) {}
int area()
{ return width*height/2; }
};
76
int main () {
Polygon * ppoly1 = new Rectangle (4,5);
Polygon * ppoly2 = new Triangle (4,5);
ppoly1->printarea();
ppoly2->printarea();
delete ppoly1;
delete ppoly2;
return 0;
} 77
Questions
•What do we gain by using the base class
in the declaration
Polygon * ppoly1 = new Rectangle (4,5);
Polygon * ppoly2 = new Triangle (4,5);
•Why not
Rectangle * ppoly1 = new Rectangle (4,5);
Triangle * ppoly2 = new Triangle (4,5);
78
int main () {
Polygon * ppoly[10];
ppoly[0] = new Rectangle (4,5);
ppoly[1] = new Triangle (4,5);
// and so on
for (int i = 0; i < 10; i++)
ppoly[i]->printarea();
// rest of the code
return 0;
} End of topic 79
Software Design and Architecture
Topic#041
END!
Software Design and Architecture
Topic#042
OOP – Object Creation and Factory Method
int main () {
Polygon * ppoly[10];
ppoly[0] = new Rectangle (4,5);
ppoly[1] = new Triangle (4,5);
// and so on
for (int i = 0; i < 10; i++)
ppoly[i]->printarea();
// rest of the code Object creation is
return 0; not polymorphic
} 82
Object creation and Factory Method
Polygon * createPolygon(char t, int w, int h) {
if (t == ‘R’)
return new Rectangle(w, h);
else if (t == ‘T’)
return new Triangle(w, h);
}
83
int main () {
Polygon * ppoly[10];
for (int i = 0; i < 10; i++) {
// get type, width, and height of the object
// to be created
ppoly[i] = createPolygon(t, w, h);
// pseudo polymorphic behavior
}
for (int i = 0; i < 10; i++)
ppoly[i]->printarea();
// rest of the code
return 0;
} End of topic 84
Software Design and Architecture
Topic#042
END!
Software Design and Architecture
Topic#043
OOP – The Magic Behind Polymorphism
•Compiler maintains two things:
SUBJECTIVE + MCQ VERY IMP
87
VTables
&Rectangle::printArea
&Rectangle::draw
Actual Objects
&Rectangle::rotate
Triangle Object .
.
Array of vptr
.
Polygons
0 Rectangle Object &Triangle::printArea
1 vptr &Triangle::draw
&Triangle::rotate
2
.
. Triangle Object .
. vptr .
. . .
. . 88
•Compiler adds additional code at two
places to maintain and use vptr. SUBJECTIVE
• Code in every constructor. This code
sets vptr of the object being created.
This code sets vptr to point to vtable of
the class.
• Code with polymorphic function call.
89
•Wherever a polymorphic call is
made, compiler inserts code to
first look for vptr. FOR MCQ
•Once vptr is fetched, vtable of
derived class can be accessed.
Using vtable, address of
derived class.
End of topic 90
Software Design and Architecture
Topic#043
END!
Software Design and Architecture
Topic#044
OOP – Implementing Composition
Event
Date Time
93
class Time
{
public:
Time();
Time(int, int);
// some setters, getters, and utility functions
void printTime();
private:
int hr;
int min;
}; 94
class Date
{
public:
Date();
Date(int, int, int);
// some setters, getters, and utility functions
void printDate();
private:
int month;
int day;
int year;
}; 95
class Event {
public:
Event(int hours = 0, int minutes = 0,
int m = 1, int d = 1, int y = 1900,
string name = “Start of 20th Century");
eidPrayer.printEventData();
independenceDay.printEventData();
//print out the data for the second object
return 0;
}
Event::Event(int hours, int minutes,
int m, int d, int y, string name)
: eventTime(hours, minutes),
eventDay(m, d, y)
{
eventName = name;
}
void Event::printEventData()
{
cout << eventName << " occurs ";
eventDay.printDate();
cout << " at ";
eventTime.printTime();
cout << endl;
}
End of topic
Software Design and Architecture
Topic#044
END!
Software Design and Architecture
Topic#045
OOP – Inheritance vs Composition
Derived_class_name::
Derived_class_constructor_name(types and parameters):
Inheritance
base_class_construcor_name(parameters)
{
set parameters which are not set by the base
class constructor;
}
Aggregate_class_name::
Aggregate_class_construcor_name(types and params):
Composition
component_class_instance(parameters)
{
set parameters which are not set by the component
class constructor;
}
•The main advantage inheritance has over
composition is that it allows objects of the
derived class to be dynamically bound in the
same hierarchy as its base classes.
IMP FOR SUBJECTIVE AND MCQ
Topic#045
END!
Software Design and Architecture
Topic#046
OOP – Implementing Uni-directional Associations
Example – Lecturer-Course Relationship
Topic#046
END!
Software Design and Architecture
Topic#047
OOP – Implementing Bi-directional Associations
•Example:
•A lecturer can be added to the course
and vice versa
•In a bi-directional associations both
classes must include a reference(via a
pointer) to the linked object.
Fakhar->addcourse(SE101);
}
void course::addlecturer(lecturer *teacher)
{
L = teacher;
L -> addcourse(this);
}
}
End of topic
Software Design and Architecture
Topic#047
END!
Software Design and Architecture
Topic#033
Object Lifetime and Visibility
Association
One instance of B is
associated with
many instances of A
Association – object creation and life-time
b2
a5 a6
Association – object creation and life-time
When the
b2
relationship is not
exclusive, the same
instance of A may a5 a6
also be linked and
accessed directly by b3
other objects.
a7
Association – object creation and life-time
When the b2
relationship is not
exclusive, the same
instance of A may a5 a6
also be linked and
accessed directly by b3
other objects.
a7
Association – object creation and life-time
b2
a5 a6
b3
a7
Association – object creation and life-time
Cardinality 1:1,
of this 1:m,
relationship
could be
or
m:m
Software Design and Architecture
Topic#033
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 048 – 061
Good Object-Oriented Design Principles
Software Design and Architecture
Topic#028
END!
Software Design and Architecture
LONG Q + SHORT AND MCQS
IMP FOR ALL
Topic#048
SOLID Design Principles - Introduction
A good design will manage
essential complexities
inherent in the problem
without adding to accidental
complexities consequential to
the solution.
Maintainable Design
·Cost of system changes is minimal
·Readily adaptable to modify existing functionality and
enhance functionality
·Design is understandable
·Changes should be local in effect
·Design should be modular
•Originally gathered
by Robert C. Martin
(aka Uncle Bob)
MCQS
Robert C. Martin
SOLID Principle - History
Topic#048
END!
Software Design and Architecture
Topic#049
SOLID Design Principles
Single Responsibility Principle (SRP)
Single Responsibility Principle (SRP)
Topic#049
END!
Software Design and Architecture
Topic#050
SOLID Design Principles
Single Responsibility Principle (SRP) - Example
class Post
{
void CreatePost(Database db, string postMessage)
{
try
{
db.Add(postMessage); Create a new post
}
catch (Exception ex)
{
db.LogError("An error occured: ", ex.ToString()); Log Error
File.WriteAllText("\LocalErrors.txt", ex.ToString());
}
}
} Multiple Responsibilities
class ErrorLogger
{
void log(string error)
{
db.LogError("An error occured: ", error);
File.WriteAllText("\LocalErrors.txt", error);
}
}
Topic#050
END!
Software Design and Architecture
Topic#051
SOLID Design Principles
Open-Closed Principle (OCP)
IMP FOR PAPERS
Topic#051
END!
Software Design and Architecture
Topic#052
SOLID Design Principles
Open-Closed Principle (OCP) - Example
class Post
{
void CreatePost(Database db, string postMessage)
{
if (postMessage.StartsWith("#"))
{
db.AddAsTag(postMessage); Case for #
}
else
{
db.Add(postMessage); Otherwise
}
}
}
What Happens if we had to add a case for @
Violates OCP
class Post class TagPost
{ {
void CreatePost(Database db, override void CreatePost(Database db,
string postMessage) string postMessage)
{ {
db.Add(postMessage); db.AddAsTag(postMessage);
} }
} }
Topic#052
END!
Software Design and Architecture
Topic#053
SOLID Design Principles
Liskov’s Substitution Principle (LSP)
Liskov Substitution Principle (LSP)
• Subtypes must be substitutable for their base types.
Topic#053
END!
Software Design and Architecture
Topic#054
SOLID Design Principles
Liskov’s Substitution Principle (LSP) - Example
class Rectangle
{
public:
virtual void SetWidth(double w) {itsWidth=w;}
virtual void SetHeight(double h) {itsHeight=w;}
double GetHeight() const {return itsHeight;}
double GetWidth() const {return itsWidth;}
private:
double itsWidth;
double itsHeight;
};
class Square : public Rectangle By setting the width
{
of a Square object, its
public:
virtual void SetWidth(double w); height will change
virtual void SetHeight(double h); correspondingly and
}; vice versa.
void Square::SetWidth(double w)
The Square object
{
Rectangle::SetWidth(w); will remain a
Rectangle::SetHeight(w); mathematically
} proper square
SetHeight will be the same as SetWidth Good? – Not really!
void g(Rectangle& r)
{
r.SetWidth(5);
r.SetHeight(4);
assert(r.GetWidth() * r.GetHeight()) == 20);
}
Works fine for a rectangle
but
assertion error if passed a square!
A violation of LSP!
Software Design and Architecture
Topic#054
END!
Software Design and Architecture
Topic#055
SOLID Design Principles
Liskov’s Substitution Principle and Inheritance
The True Meanings of IsA Relationship
Validity is not Intrinsic
•A model, viewed in isolation, cannot
be meaningfully validated.
• No!
• Why?
• Because the behavior of a Square object is not
consistent with the behavior of a Rectangle object.
Topic#055
END!
Software Design and Architecture
Topic#056
SOLID Design Principles
Interface Segregation Principle (ISP)
Interface Segregation Principle (ISP)
• Clients should not be forced to depend upon interfaces that they do
not use
CP1 CP2 CP3
OPS
--------------------------
OP1, OP2, OP3
Topic#056
END!
Software Design and Architecture
Topic#057
SOLID Design Principles
Interface Segregation Principle (ISP) - Example
interface IPost
Initially an IPost interface
{ with the signature of a
void CreatePost(); CreatePost() method.
}
interface IPost
{
void CreatePost(); Later on, a new method
void ReadPost(); ReadPost() added to it
}
Violation of ISP!
Old clients do not need the new interface
it is quiz
Complying to ISP!
Software Design and Architecture
Topic#057
END!
Software Design and Architecture
Topic#058
SOLID Design Principles
Dependency Inversion Principle (DIP)
The Dependency-Inversion Principle (DIP)
1. High-level modules should not depend on low-level
modules. Both should depend on abstractions.
2. Abstractions should not depend upon details. Details
should depend upon abstractions.
Topic#058
END!
Software Design and Architecture
Topic#059
SOLID Design Principles
Dependency Inversion Principle (DIP) - Example
class Post
{
private ErrorLogger errorLogger = new ErrorLogger(); Dependency
void CreatePost(Database db, string postMessage)
{
try
We create the ErrorLogger instance
{ from within the Post class.
db.Add(postMessage);
} This is a violation of the dependency
catch (Exception ex) inversion principle.
{
errorLogger.log(ex.ToString())
} If we wanted to use a different kind
} of logger, we would have to modify
} the Post class.
class Post
{
private Logger _logger;
Topic#059
END!
Software Design and Architecture
Topic#060
Good OO design principles
Law of Demeter (LoD)
Law of Demeter – A Style Rule for building systems
• Demeter Origins
• Proposed by The Demeter Research Group in 1987
• "Law of Demeter" Paper
• Lieberherr, Karl. J. and Holland, I., “Assuring good
style for object-oriented programs”, IEEE Software,
September 1989, pp 38-48
• Covered in many major books on OO design and
programming.
Reduces coupling and improves maintainability
Law of Demeter – A Style Rule for building systems
Topic#060
END!
Software Design and Architecture
Topic#061
Good OO design principles
Law of Demeter (LoD) - Example
Register needs to find out the amount of the payment
// same as:
// Money amount = sale.getPayment().getTenderedAmount();
// chain calls
}
getTenderedAmount() getPayment()
:Payment :Register :Sale
Register Sale Payment
Model vs Actual
getTenderedAmount() getPayment()
:Payment :Register :Sale
paymentAmount() becomeComplete()
makeLineItem() getTenderedAmount()
endSale()
enterItem() makePayment()
makePayment() getTotal()
... getPayment
...
add a method to
get a payment
LoD – Don’t Talk to Strangers
If getPayment() in Sale would invoke getTenderedAmount() in Payment, and
return the payment amount, then we can de-couple Register from Payment
make the solution more robust, less sensitive to changes, less coupling
Software Design and Architecture
Topic#061
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 062 – 068
Object-Oriented Design
Solutions to some general design problems
Software Design and Architecture
Topic#062
Action-Oriented Design in the Disguise of object-Oriented
Design
Good OOD practices
• High cohesion and low coupling
• An object must be able to answer the following:
• who I am? identity
• Principle of delegation
Design Challenges with OO Paradigm
• Poorly distributed system intelligence
• god classes
• Behavioral form - can’t answer what I know
• Data form - can’t answer what I do
4
god class problem – behavioral form
• Action-oriented in the disguise of object-oriented
• Central control mechanism
• Super object that does most of the work leaving
minor details to a collection of trivial classes
Topic#062
END!
Software Design and Architecture
Topic#063
Handling Poorly Distributed System Intelligence
Desired
Temp
actualTemp()
Actual Heat Flow
Furnace
Temp Regulator
Occupancy
8
Room
Desired
desiredTemp()
Temp
actualTemp() Heat Flow
Actual Furnace
anyonePresent() Regulator
Temp
Occupancy
9
Room
Desired
Temp
Occupancy
10
Software Design and Architecture
Topic#063
END!
Software Design and Architecture
Topic#064
Modelling Policy – Jacobson’s Heuristic
Student – Course – Course Offering
Policy Information
Requires data of two classes to make a decision. 13
Course Student Course Student
check() getCourses() getPrereqs() check()
PreRequisites Courses PreRequisites Courses
addStudent() addStudent()
CourseOffering CourseOffering
14
Jocobson’s Heuristic
Policy information should not be
placed inside of classes involved in
the policy decision because it
renders them un-reusable by binding
them to the domain that sets the
policy.
15
Controller Class
Course Student
getPrereqs() getCourses()
PreRequisites Courses
What I know?
check()
PrereqChecker
addStudent()
CourseOffering
16
Software Design and Architecture
Topic#064
END!
Software Design and Architecture
Topic#065
Handling roles - Player-Role Pattern
Roles
Topic#065
END!
Software Design and Architecture
Topic#066
Handling multiple discriminators using Player-Role
Pattern
• A discriminator is a label that
describes the criteria used in the
specialization
habitat typeOfFood
habitat
AquaticAnimal LandAnimal
typeOfFood typeOfFood
habitat
AquaticAnimal LandAnimal
typeOfFood typeOfFood
habitat
AquaticAnimal LandAnimal
typeOfFood typeOfFood
habitat
AquaticAnimal LandAnimal
typeOfFood typeOfFood
habitat typeOfFood
habitat typeOfFood
habitat typeOfFood
typeOfFood habitat
Topic#066
END!
Software Design and Architecture
Topic#067
Abstraction-Occurrence Pattern
•Problem
• A library has multiple copies of the same book.
• How to model?
LibraryItem
name
author
isbn
publicationDate
libOfCongress
barCodeNumber
•Problem
• A library has multiple copies of the same book.
• How to model?
Title
name
author
isbn
publicationDate
libOfCongress
IsA
LibraryItem Relationship?
barCodeNumber
•Problem
• A library has multiple copies of the same book.
• How to model?
Title LibraryItem
*
name AccNo
author
isbn
publicationDate
libOfCongress
The Abstraction-Occurrence Pattern
• Context:
• Often in a domain model you find a set of related objects
(occurrences).
• The members of such a set share common information
• but also differ from each other in important ways.
• Problem:
• What is the best way to represent such sets of occurrences in a class
diagram?
• Forces:
• You want to represent the members of each set of occurrences
without duplicating the common information
Abstraction-Occurrence - Examples
TVSeries Episode
*
seriesName number
producer title
storySynopsis
Square variant
ScheduledTrain *
SpecificTrain
number date
* *
ScheduledLeg *
SpecificLeg
scheduledDepTime actualDepTime
scheduledArrTime actualArrTime
* *
origin destination
Station
Software Design and Architecture
Topic#067
END!
Software Design and Architecture
Topic#068
Reflexive Associations
Reflexive associations
An association to connect a class to itself
successor
*
* Course isMutuallyExclusiveWith
*
*
prerequisite
• Examples:
• parent-child, supervisor-subordinate, and predecessor-
successor, course-prerequisite
Asymmetric Reflexive Association
class Person {
Person *parents[2];
…
};
Asymmetric Reflexive Association
// Example - asymmetric association with role name
// on the other end
class Person {
Person *parents[2];
vector <Person *> child;
…
}
Symmetric Reflexive Association
• There is no logical difference in the semantics of each
association end
• Example:
• mutually exclusive courses
• students who have taken one course cannot take
another in the set
• If course A is mutually exclusive with B, then course
B is mutually exclusive with A
Symmetric Reflexive Association
class Course {
Course *mutuallyExclusiveWith[3];
};
Software Design and Architecture
Topic#068
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 069 – 075
Design Patterns
Software Design and Architecture
Topic#069
Design Patterns – Introduction
•Good OOD is more than just knowing
and applying concepts like abstraction,
inheritance, and polymorphism
Topic#069
END!
Software Design and Architecture
Topic#070
Elements of design patterns
Elements of Design Patterns
• Design patterns have four essential elements:
• Pattern name
• Problem
• Solution
• Consequences
Pattern Name
• A handle used to describe:
• a design problem
• its solutions
• its consequences
• Increases design vocabulary
• Makes it possible to design at a higher level of abstraction
• Enhances communication
• “The Hardest part of programming is coming up with good
variable [function, and type] names.”
Factory Method
Product
Creator <<interface>>
Product
FactoryMethod()
Operation()
…
Product =
factoryMethod();
…
Product1
Creator1 <<Create>>
FactoryMethod()
Problem
• Describes when to apply the pattern
• Explains the problem and its context
• May describe specific design problems and/or
object structures
• May contain a list of preconditions that must
be met before it makes sense to apply the
pattern
Solution
• Describes the elements that make up the
• design
• relationships
• responsibilities
• collaborations
• Abstract description of design problems and how
the pattern solves it
• Does not describe specific concrete implementation
Consequences
• Results and trade-offs of applying the pattern
• Critical for:
• evaluating design alternatives
• understanding costs
• understanding benefits of applying the pattern
• Includes the impacts of a pattern on a system’s:
• flexibility
• extensibility
• portability
Design Pattern Descriptions
• Name and Classification: Essence of pattern
• Intent: What it does, its rationale, its context
• AKA: Other well-known names
• Motivation: Scenario illustrates a design problem
• Applicability: Situations where pattern can be applied
• Structure: Class and interaction diagrams
• Participants: Objects/classes and their responsibilities
• Collaborations: How participants collaborate
• Consequences: Trade-offs and results
• Implementation: Pitfalls, hints, techniques, etc.
• Sample Code
• Known Uses: Examples of pattern in real systems
• Related Patterns: Closely related patterns
Software Design and Architecture
Topic#070
END!
Software Design and Architecture
Topic#071
Categories of Design Patterns
Categories of Patterns
All quiz
• Creational patterns (5)
• Deal with initializing and configuring classes and objects
• Structural patterns (8)
• Deal with decoupling interface and implementation of
classes and objects
• Composition of classes or objects
• Behavioural patterns (11)
• Deal with dynamic interactions among societies of classes
and objects
• How they distribute responsibility
Pattern Types
• Class Patterns (4)
• Deal with relationships between classes and their
subclasses
• Established through inheritance, so they are static-
fixed at compile-time
• Object Patterns (20)
• Deal with object relationships
• Established through association
• Can be changed at run-time and are more dynamic
Purpose
Creational Structural Behavioural
Scope Class • Factory • Adapter • Interpreter
method (class) • Template method
Object • Abstract • Adapter • Chain of responsibility
factory (object) • Command
• Builder • Bridge • Iterator
• Prototype • Composite • Mediator
• Singleton • Decorator • Memento
• Façade • Observer
• Flyweight • State
• Proxy • Strategy
• Visitor
Software Design and Architecture
Topic#071
END!
Software Design and Architecture
Topic#072
Benefits and drawbacks of design patterns
Benefits of Design Patterns
• Design patterns enable large-scale reuse of
software architectures and also help document
systems
• Patterns explicitly capture expert knowledge and
design trade-offs and make it more widely available
• Pattern names form a common vocabulary
• Patterns help improve developer communication
• Patterns help ease the transition to OO technology
Drawbacks to Design Patterns
• Patterns do not lead to direct code reuse
• Patterns are deceptively simple
• Patterns are validated by experience and
discussion rather than by automated testing
• Integrating patterns into a software development
process is a human-intensive activity.
Design Patterns are NOT
• Designs that can be encoded in classes and reused
as is (i.e., linked lists, hash tables)
• Complex domain-specific designs (for an entire
application or subsystem)
• They are:
• “Descriptions of communicating objects and classes
that are customized to solve a general design problem
in a particular context.”
Software Design and Architecture
Topic#072
END!
Software Design and Architecture
Topic#073
Singleton Design Pattern
The Singleton Pattern
• Context:
• It is very common to find classes for which only one instance
should exist (singleton)
• Problem:
• How do you ensure that it is never possible to create more than
one instance of a singleton class?
• Forces:
• The use of a public constructor cannot guarantee that no more
than one instance will be created.
• The singleton instance must also be accessible to all classes that
require it
Singleton - Uses
Use the Singleton when:
• There must be exactly one (or fixed number) instance of
the class and it must be accessible to clients from a well-
known access point
Singleton - Structure
S in g le to n
s ta tic In s ta n c e ( )
S in g le t o n O p e r a tio n ( )
G e tS in g le to n D a t a ( )
s t a t ic u n iq u e I n s ta n c e
s in g le t o n D a ta
Implementation
Class Singleton { Singleton* Singleton::
public: _instance= NULL;
static singleton* Instance();
protected: Singleton* Singleton::Instance() {
if (_instance == NULL) {
Singleton();
_instance = new Singleton;
private: }
static singleton* _instance; return _instance;
}; }
Software Design and Architecture
Topic#073
END!
Software Design and Architecture
Topic#074
Strategy Design Pattern
SimDuck
Add fly()
• What about
a rubber
duck?
Rubber Duck
Violation of LSP
Another duck
Violation of LSP
Multiple
Interfaces
Associate
Algorithm
s
public abstract class Duck {
FlyBehavior flyBehavior;
QuackBehavior quackBehavior;
public Duck() { }
public abstract void display();
public void performFly() {
flyBehavior.fly();
}
public void performQuack() {
quackBehavior.quack();
}
// other
public class MallardDuck extends Duck {
public MallardDuck() {
quackBehavior = new Quack();
flyBehavior = new fly();
}
// other
}
Strategy Pattern
All quiz
Defines a family of
algorithms, encapsulates
each one, and makes
them interchangeable.
Strategy lets the
algorithm vary
independently from
clients that use it.
Software Design and Architecture
Topic#074
END!
Software Design and Architecture
Topic#075
Object-Morphing and Strategy Pattern
Employee
benefits()
TraineeEmployee RegularEmployee
benefits() benefits()
Object Morphing
Avoiding having instances change class
• Object Morphing
• When an instance changes its class
• An instance should never need to change class
• You have to destroy the old one and create a new one.
• What happens to associated objects?
• You have to make sure that all links that connected
to the old object now connect to the new one.
EmployeeBenefits
Employee
benefits()
TraineeEmployeeBenefits RegularEmployeeBenefits
benefits() benefits()
Topic#075
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 076 – 082
Design Patterns – Part II
Software Design and Architecture
All quiz
Topic#076
Façade Design Pattern
Problem
•There is a legacy application written in C
•There is a rich library of functionality
that is very difficult to be re-written
•A new GUI-based interface needs to be
added to the application
Problem
The application needs to be
“object-orientized” to make it
communicate/compatible with the
rest of a newly built system.
• Structural Pattern
• Provides a unified interface to a set of interfaces in a
subsystem.
• Defines a higher-level interface that makes the
subsystem easier to use.
• Wraps a complicated subsystem with a simpler
interface.
Facade
• The principal front of a building,
that faces on to a street or open
space
• A deceptive outward appearance
General-building-façade: From Wikimedia Commons
Facade Pattern
• Involves a single class which provides simplified
methods required by client and delegates calls to
methods of existing system classes.
• Can be used to add an interface to existing system to
hide its complexities.
Facade objects
are often
Singletons
because only
one Facade
object is
required.
Software Design and Architecture
Topic#076
END!
Software Design and Architecture
Topic#077
Modeling Sate Machine
END MID TERM SYLLABUS
Gumball Machine
By putting CPUs into
their machines, they can
increase sales, monitor
inventory over the
network and measure
customer satisfaction
more accurately.
Gumball Machine – Sate Diagram
Implementing State Machines
Step 1: Identify states
1.SOLD_OUT
2.NO_QUARTERS
3.HAS_QUARTERS
4.SOLD
Implementing State Machines
Step 2: Create instance variables to hold state
1.Inserts quarters
2.Turns crank
3.Dispense
4.Ejects Quarters
Implementing State Machines
Step 6: Create a method that acts as the state machine
• Gumball machine class
• A method for each action
• We use conditionals to determine what
behavior is appropriate in each state
public void insertQuarter ( ) {
if (state == HAS_QUARTER) {
System.out.println(“ Can’t insert another quarter”);
} else if (state == SOLD_OUT) {
System.out.println(
“ Can’t insert a quarter, the machine is sold out”);
} else if (state == SOLD) {
System.out.println (
“ Please wait we are getting you a gumball”);
} else if (state == NO_QUARTER) {
state = HAS_QUARTER;
System.out.println(“You inserted a quarter”);
}
}
public void ejectQuarter ( ) { … }
public void turnCrank ( ) { … }
public void dispense ( ) { … }
public void somthingElse ( ) { … }
Topic#077
END!
Software Design and Architecture
Topic#078
State Design Pattern
The State Pattern
The State Pattern allows an
object to alter its behavior when
its internal state changes. The
object will appear to change its
class.
State Design Pattern: Motivation
• The State pattern is useful when you want to
have an object represent the state of an
application, and you want to change the state by
changing that object.
• The State pattern is intended to provide a
mechanism to allow an object to alter its
behavior in response to internal state changes.
State Design Pattern: Motivation
• To the client, it appears as though the object has
changed its class.
• The benefit of the State pattern is that state-
specific logic is localized in classes that represent
that state.
Context State
request() handle()
state.handle()
ConcreteStateA ConcreteStateB
handle() handle()
request() handle()
state.handle()
ConcreteStateA ConcreteStateB
handle() handle()
request() handle()
state.handle()
ConcreteStateA ConcreteStateB
handle() handle()
request() handle()
state.handle()
ConcreteStateA ConcreteStateB
handle() handle()
request() handle()
state.handle()
ConcreteStateA ConcreteStateB
handle() handle()
request() handle()
state.handle()
ConcreteStateA ConcreteStateB
handle() handle()
request() handle()
state.handle()
ConcreteStateA ConcreteStateB
handle() handle()
request() handle()
state.handle()
ConcreteStateA ConcreteStateB
handle() handle()
request() handle()
state.handle()
ConcreteStateA ConcreteStateB
handle() handle()
Topic#078
END!
Software Design and Architecture
Topic#079
State Design Pattern - Example
Gumball Machine - The new design
1. Define a State interface that contains a method for
every action in the Gumball Machine
2. Implement a State class for every state of the
machine. These classes will be responsible for the
behavior of the machine when it is in the
corresponding state
• We are going to get rid of all the conditional code and
instead delegate to the state class to do all the work
State
insertQuarter()
ejectQuarter()
turnCrank()
dispense()
Topic#079
END!
Software Design and Architecture
Topic#080
Comparison of Strategy and State Design Patterns
Everything seems satisfactory until we think
about the life of the traineeEmployee object
Object Morphing
Strategy vs State
State vs Strategy
•They are both examples of association
with delegation
•The difference between the State and
Strategy patterns is one of intent
State Strategy
• Set of behaviors encapsulated in • Client usually specifies the strategy
state objects; object that the context is associated
• At any time the context is with.
delegating to one of those states. • While the pattern provides the flexibility
• Over time, the current state to change the strategy object at run
changes across the set of state time, there is one strategy object that is
objects to reflect the internal most appropriate for a context object.
state of the context, so the • Flexible alternative to subclassing: if you
context’s behavior changes over use inheritance to define the behavior of
time. Client knows very little, if a class, you are stuck with it even if you
anything, about the state objects need to change it.
• Alternative to putting a lots of • With strategy you can change the
conditional in the context behavior by associating it with different
objects
Software Design and Architecture
Topic#080
END!
Software Design and Architecture
Topic#081
Composite Design Pattern
Employee
0..1
«NonSuperiorNode» «SuperiorNode»
0..1 0..1
*
«Node»
«subordinate»
0..1
«NonSuperiorNode» «SuperiorNode»
The General Hierarchy Pattern
Employee * supervises
0..1
0..1
File Directory
•The difference between a tree data
structure and the composite pattern
Topic#081
END!
Software Design and Architecture
Topic#082
Observer Design Pattern
Excel - Example
a b c b
x 6030 10
y 503020 a c
z 8010 10 a b c
•Observer
• the object which depends on a subject and
updates according to its subject's state.
Observer Pattern - Example
a b c b
Observers
x 6030 10
y 503020 a c
z 8010 10 a b c
a = 50%
Subject b = 30%
c = 20%
requests, modifications
change notification
Observer Pattern - UML
observers
Subject Observer
Attach(Observer) Update()
Detach(Observer)
Notify() for all o in
observers {
o -> Update()}
ConcreteObserver
observerState =
Update()
subject subject->GetState()
ConcreteSubject observerState
SetState()
GetState()
return subjectState
subjectState
Observer Pattern - UML
observers
Subject Observer
Attach(Observer) Update()
Detach(Observer)
Notify() for all o in
observers {
o -> Update()}
ConcreteObserver
observerState =
Update()
subject subject->GetState()
ConcreteSubject observerState
SetState()
GetState()
return subjectState
subjectState
Subject has a list of observers
Interfaces for attaching/detaching an observer
Observer Pattern - UML
observers
Subject Observer
Attach(Observer) Update()
Detach(Observer)
Notify() for all o in
observers {
o -> Update()}
ConcreteObserver
observerState =
Update()
subject subject->GetState()
ConcreteSubject observerState
SetState()
GetState()
return subjectState
subjectState
Observer has an updating interface for objects
that gets notified of changes in a subject
Observer Pattern - UML
observers
Subject Observer
Attach(Observer) Update()
Detach(Observer)
Notify() for all o in
observers {
o -> Update()}
ConcreteObserver
observerState =
Update()
subject subject->GetState()
ConcreteSubject observerState
SetState()
GetState()
return subjectState
subjectState Concrete Subject Stores “state of interest” to
observers and Sends notification when state
changes
Observer Pattern - UML
observers
Subject Observer
Attach(Observer) Update()
Detach(Observer)
Notify() for all o in
observers {
o -> Update()}
ConcreteObserver
observerState =
Update()
subject subject->GetState()
ConcreteSubject observerState
SetState()
GetState()
return subjectState
subjectState
Concrete Observer Implements updating
interface
Observer Pattern - UML
observers
Subject Observer
Attach(Observer) Update()
Detach(Observer)
Notify() for all o in
observers {
o -> Update()}
ConcreteObserver
observerState =
Update()
subject subject->GetState()
ConcreteSubject observerState
SetState()
GetState()
return subjectState
subjectState
A number of Observers “register” to receive
notifications of changes to the Subject.
Observer Pattern - UML
observers
Subject Observer
Attach(Observer) Update()
Detach(Observer)
Notify() for all o in
observers {
o -> Update()}
ConcreteObserver
observerState =
Update()
subject subject->GetState()
ConcreteSubject observerState
SetState()
GetState()
return subjectState
subjectState
A number of Observers “register” to receive
notifications of changes to the Subject.
Observer Pattern - UML
observers
Subject Observer
Attach(Observer) Update()
Detach(Observer)
Notify() for all o in
observers {
o -> Update()}
ConcreteObserver
observerState =
Update()
subject subject->GetState()
ConcreteSubject observerState
SetState()
GetState()
return subjectState
subjectState
When a certain event or “change” in Subject
occurs, all Observers are “notified’.
Observer Pattern - Consequences
• Loosely Coupled
• Reuse subjects without reusing their observers, and vice versa
• Add observers without modifying the subject or other
observers
Topic#082
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 083 – 092
Refactoring – Part I
Software Design and Architecture
Topic#083
Refactoring Introduction
What is Refactoring?
• Refactoring is the process of changing a
software system such that:
• the external behavior of the system does not
change
• the internal structure of the system is
improved
• This is sometimes called “Improving the design
after it has been written”
3
Why is Refactoring Useful?
• The idea behind refactoring is to acknowledge that
it will be difficult to get a design right the first time
• as a program’s requirements change, the design may
need to change
• refactoring provides techniques for evolving the design
in small incremental steps
5
Refactoring Benefits
• Refactoring improves the design of software
without refactoring, a design will “decay” as
people make changes to a software system
• Refactoring makes software easier to
understand because structure is improved,
duplicated code is eliminated, etc.
6
Refactoring Benefits
• Refactoring helps you find bugs
• Refactoring promotes a deep understanding of
the code at hand, and this understanding aids
the programmer in finding bugs and
anticipating potential bugs
• Refactoring helps you program faster because a
good design enables progress
7
Software Design and Architecture
Topic#083
END!
Software Design and Architecture
Topic#084
Refactoring – A simple example
A (Very) Simple Example
Consolidate Duplicate Conditional Fragments
if (isSpecialDeal()) {
if (isSpecialDeal())
total = price * 0.95;
total = price * 0.95;
send ();
else
} total = price * 0.98;
else {
total = price * 0.98; send ();
send ();
}
10
A (Very) Simple Example
Better Still
if (isSpecialDeal()) if (isSpecialDeal())
total = price * 0.95; factor = 0.95;
else else
total = price * 0.98; factor = 0.98;
Topic#084
END!
Software Design and Architecture
Topic#085
Refactoring vs Rewriting and optimization
Refactoring versus Rewriting
•Code has to work mostly correctly
before you refactor.
•If the current code just does not
work, do not refactor.
•Rewrite instead!
14
Optimization versus Refactoring
• The purpose of refactoring is
• to make software easier to understand and
modify
• Performance optimizations often involve
making code harder to understand (but
faster!)
15
Optimization versus Refactoring
for (i=0; i < N; i++) if (cond1) {
{ for (i=0; i < N; i++) {
//1…
// condition does not // xyz
// change inside the }
else if (cond2) {
// loop
for (i=0; i < N; i++) {
//2…
if (cond1) {//1…} // xyz
}
else if (cond2) {//2…} else if (cond2) {
else {//3…} for (i=0; i < N; i++) {
//2…
// xyz // xyz
} }
} 16
Software Design and Architecture
Topic#085
END!
Software Design and Architecture
Topic#086
Making Refactoring Safe
How do you make refactoring safe?
1. use refactoring “patterns”
• Fowler’s book assigns “names” to
refactorings in the same way that the GoF’s
book assigned names to patterns
19
How do you make refactoring safe?
2. Test constantly!
• This ties into the extreme programming paradigm,
you write tests before you write code, after you
refactor code, you run the tests and make sure
they all still pass
Topic#086
END!
Software Design and Architecture
Topic#087
Code Smells – Bad smells in code
Refactoring: Where to Start?
23
“if it stinks, change it”
Grandma Beck, discussing child-rearing philosophy
24
Categories of bad smells
•Bloaters (5)
•Object-orientation abusers (4)
•Change preventers (3)
•Dispensables (5)
•Couplers (5)
Software Design and Architecture
Topic#087
END!
Software Design and Architecture
Topic#088
Code Smells – Bloaters
Bloaters (5)
• Bloaters are code, methods and classes that have
increased to such enormous proportions that they
are hard to work with.
30
• Large Class
• Large classes try to do too much, which
reduces cohesion
• violates SRP
• Long Parameter List
• hard to understand, can become inconsistent
• Symptom of behavioral form of god class
31
• Data Clumps
• attributes that clump together but are not part
of the same class
• Lack of cohesion – SRP
• Primitive Obsession
• characterized by a reluctance to use classes
instead of primitive data types
32
Software Design and Architecture
Topic#088
END!
Software Design and Architecture
Topic#089
Code Smells – Object-orientation abusers
Object-orientation Abusers (4)
• Incomplete or incorrect application of object-
oriented programming principles
• Switch statement
• Temporary field
• Refused bequest
• Alternative classes with different interfaces
• Switch Statements
• Switch statements are often duplicated in
code; they can typically be replaced by use of
polymorphism (let OO do your selection for
you!)
• Typically a place where strategy or state pattern
should have been used
• Temporary Field
• An attribute of an object is only set in certain
circumstances; but an object should need all
of its attributes
• Refused Bequest
• A subclass ignores most of the functionality
provided by its superclass
• violates LSP
Topic#089
END!
Software Design and Architecture
Topic#090
Code Smells – Change Preventers
Change Preventers (3)
• These smells mean that if you need to change
something in one place in your code, you have to
make many changes in other places too.
• Program development becomes much more
complicated and expensive as a result.
• Divergent change
• Shotgun surgery
• Parallel inheritance hierarchies
• Divergent Change
• Deals with cohesion; symptom: one type of
change requires changing one subset of
methods; another type of change requires
changing another subset
• violates SRP
• Shotgun Surgery
• a change requires lots of little changes in a lot
of different classes
• Parallel Inheritance Hierarchies
• Similar to Shotgun Surgery; each time I add a
subclass to one hierarchy, I need to do it for all
related hierarchies
Software Design and Architecture
Topic#090
END!
Software Design and Architecture
Topic#091
Code Smells – Dispensables
Dispensables (5)
• A dispensable is something pointless and unneeded
whose absence would make the code cleaner, more
efficient and easier to understand.
• Comments
• Duplicated code
• Lazy class
• Data class
• Speculative generality
• Comments (!)
• Comments are sometimes used to hide bad code
• “…comments often are used as a deodorant” (!)
• Duplicated Code
• bad because if you modify one instance of
duplicated code but not the others, you (may)
have introduced a bug!
• Lazy Class
• Each class costs money to maintain and
understand.
• A class that no longer “pays its way”
• e.g. may be a class that was downsized by
refactoring, or represented planned
functionality that did not pan out
• Data Class
• These are classes that have fields, getting and
setting methods for the fields, and nothing else;
they are data holders, but objects should be about
data AND behavior
• Symptom of data form of god class
• Speculative Generality
• “Oh I think we need the ability to do this kind of
thing someday”
Software Design and Architecture
Topic#091
END!
Software Design and Architecture
Topic#092
Code Smells – Couplers
Couplers (5)
• All the smells in this group contribute to excessive
coupling between classes or show what happens if
coupling is replaced by excessive delegation.
• Feature envy
• Inappropriate intimacy
• Message chain
• Middle man
• Incomplete library class
• Feature Envy
• A method requires lots of information from
some other class (move it closer!)
• Symptom of behavioral form of god class
• Inappropriate Intimacy
• Pairs of classes that know too much about
each other’s private details
• Message Chains
• a client asks an object for another object and
then asks that object for another object etc.
Bad because client depends on the structure
of the navigation
• violates LoD
• Middle Man
• If a class is delegating more than half of its
responsibilities to another class, do you really
need it?
Topic#092
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 093 – 098
Refactoring – Part II
Software Design and Architecture
Topic#093
Refactoring – The Catalog
Refactoring
• How to fix a code smell
7
Software Design and Architecture
Topic#093
END!
Software Design and Architecture
Topic#094
Refactoring – Extract Method
Extract Method
10
Extract Method, continued
void printOwing(double amount) {
printBanner()
//print details
System.out.println(“name: ” + _name);
System.out.println(“amount: ” + amount);
}
11
Extract Method, continued
12
Extract Method, continued
void printOwing(double amount) {
printBanner()
printDetails(amount)
}
13
Software Design and Architecture
Topic#094
END!
Software Design and Architecture
Topic#095
Refactoring – Replace Temp with Query
Replace Temp with Query
17
double basePrice() {
return _quantity * _itemPrice;
}
Replace Temp with Query
19
Software Design and Architecture
Topic#095
END!
Software Design and Architecture
Topic#096
Refactoring – Move Method
Move Method
Topic#096
END!
Software Design and Architecture
Topic#097
Refactoring – Replace Conditional with Polymorphism
Replace Conditional with Polymorphism
Bird
getSpeed()
28
Software Design and Architecture
Topic#097
END!
Software Design and Architecture
Topic#098
Refactoring – Introduce Null Object
Introduce Null Object
31
Introduce Null Object
if (customer == null) {
name = “occupant”
} else {
name = customer.getName()
}
if (customer == null) {
…
32
Introduce Null Object
Customer
getName()
Null Customer
getName()
33
Introduce Null Object
if (customer.isNull())
name = “occupant”;
else
name = customer.getName();
customer.getName();
The conditional goes away entirely!!
34
Software Design and Architecture
Topic#098
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 099 – 109
Refactoring – Part III
Software Design and Architecture
Topic#099
Refactoring – Example Part I
A Video Store
Refactoring Example
• A simple program for a video store
• Movie
• Rental
• Customer
• Program is told which movies a customer rented and
for how long and it then calculates:
• the charges
• Frequent renter points
• Customer object can print a statement (in ASCII)
3
Refactoring Example
• We want to add a new method to generate an HTML
statement
4
Initial Class Diagram
Movie Rental Customer
1 * daysRented: int * 1
priceCode: int
statement()
5
Initial Class Diagram
Movie Rental Customer
1 * daysRented: int * 1
priceCode: int
statement()
6
Initial Class Diagram
Movie Rental Customer
1 * daysRented: int * 1
priceCode: int
statement()
7
public class Movie {
public static final int CHILDREN = 2;
public static final int REGULAR = 0;
public static final int NEW_RELEASE = 1;
private String _title;
private int _priceCode;
public Movie(String title, int priceCode) {
_title = title;
_priceCode = priceCode
}
public int getPriceCode() { return _priceCode; }
public String getTitle() { return _title; }
public void setPriceCode(int priceCode) {
_priceCode = priceCode;
}
} 8
class Rental {
private Movie _movie;
private int _daysRented;
public Rental(Movie movie, int daysRented) {
_movie = movie;
_daysRented = daysRented;
}
public int getdaysRented() { return _daysRented; }
public Movie getMovie() { return _movie; }
}
9
class Customer {
private String _name;
private Vector _rentals = new Vector();
public Customer(String name) { _name = name; }
public String getName() { return _name; }
public void addRental (Rental arg) {
_rentals.addElement(arg);
}
public String statement();
}
10
public String statement() {
double totalAmount = 0;
int frequentRenterPoints = 0;
Enumeration rentals = _rentals.elements();
String result = “Rental record for ”+getName() + “\n”;
while (rentals.hasMoreElements()) {
double thisAmount = 0;
Rental each = (Rental) rentals.nextElement();
11
// determine amounts for each line
switch (each.getMovie().getPriceCode()) {
case Movie.REGULAR:
thisAmount += 2;
if (each.getDaysRented() > 2)
thisAmount += (each.getDaysRented() - 2) *1.5;
break;
case Movie.NEW_RELAESE:
thisAmount += each.getDaysRented() * 3;
break;
case Movie.CHILDREN:
thisAmount += 1.5;
if (each.getDaysRented() > 3)
thisAmount += (each.getDaysRented() - 3) *1.5;
break;
}
12
// add frequent renter points
frequentRenterPoints++;
// add bonus for two day new release rental
if ((each.getMovie().getPriceCode() ==
Movie.NEW_RELEASE) &&
each.getDaysRented() > 1)
frequentRenterPoints++;
// show figures for this rental
result += “\t” + each.getMovie().getTitle() + “\t” +
String.valueOf(thisAmount) + “\n”;
totalAmount += thisAmount;
} // end while
13
// add footer lines
14
public String statement() {
double totalAmount = 0;
int frequentRenterPoints = 0;
Enumeration rentals = _rentals.elements();
String result = “Rental record for ” + getName() + “\n”;
while (rentals.hasMoreElements()) {
double thisAmount = 0;
Rental each = (Rental) rentals.nextElement();
// determine amounts for each line
switch (each.getMovie().getPriceCode()) {
case Movie.REGULAR:
thisAmount += 2;
if (each.getDaysRented() > 2)
thisAmount += (each.getDaysRented() - 2) *1.5;
break;
case Movie.NEW_RELAESE:
thisAmount += each.getDaysRented() * 3;
break;
case Movie.CHILDREN:
thisAmount += 1.5;
if (each.getDaysRented() > 3)
thisAmount += (each.getDaysRented() - 3) *1.5;
break;
}
Topic#099
END!
Software Design and Architecture
Topic#100
Refactoring – Example Part II
Extract Method
How to start?
• We want to decompose statement() into
smaller pieces which are easier to manage
and move around.
• We’ll start with “Extract Method”
• target the switch statement first
19
switch (each.getMovie().getPriceCode()) {
case Movie.REGULAR:
thisAmount += 2;
if (each.getDaysRented() > 2)
thisAmount += (each.getDaysRented() - 2) *1.5;
break;
case Movie.NEW_RELAESE:
thisAmount += each.getDaysRented() * 3;
break;
case Movie.CHILDREN:
thisAmount += 1.5;
if (each.getDaysRented() > 3)
thisAmount += (each.getDaysRented() - 3) *1.5;
break;
}
Extract method 20
switch (each.getMovie().getPriceCode()) {
case Movie.REGULAR:
thisAmount += 2;
if (each.getDaysRented() > 2)
thisAmount += (each.getDaysRented() - 2) *1.5;
break;
case Movie.NEW_RELAESE:
thisAmount += each.getDaysRented() * 3;
break;
case Movie.CHILDREN:
thisAmount += 1.5;
if (each.getDaysRented() > 3)
thisAmount += (each.getDaysRented() - 3) *1.5;
break;
}
Topic#100
END!
Software Design and Architecture
Topic#101
Refactoring – Example Part III
Extract Method - Pitfalls
Be careful!
• Pitfalls
• be careful about return types; in the original
statement(), thisAmount is a double, but it
would be easy to make a mistake of having the
new method return an int. This will cause
rounding-off error.
• Always remember to test after each change.
29
private double amountFor(Rental each)
double thisAmount = 0;
switch (each.getMovie().getPriceCode()) {
case Movie.REGULAR:
thisAmount += 2;
if (each.getDaysRented() > 2)
thisAmount += (each.getDaysRented() - 2) *1.5;
break;
case Movie.NEW_RELAESE:
thisAmount += each.getDaysRented() * 3;
break;
case Movie.CHILDREN:
thisAmount += 1.5;
if (each.getDaysRented() > 3)
thisAmount += (each.getDaysRented() - 3) *1.5;
break;
}
return thisAmount;
}
30
Software Design and Architecture
Topic#101
END!
Software Design and Architecture
Topic#102
Refactoring – Example Part IV
Extract Method – Making it More Readable
private double amountFor(Rental each) look at the
double thisAmount = 0; variable names
switch (each.getMovie().getPriceCode()) {
case Movie.REGULAR: and use more
thisAmount += 2;
if (each.getDaysRented() > 2)
suitable ones
thisAmount += (each.getDaysRented() - 2) *1.5;
break;
case Movie.NEW_RELAESE:
thisAmount += each.getDaysRented() * 3;
break;
case Movie.CHILDREN:
thisAmount += 1.5;
if (each.getDaysRented() > 3)
thisAmount += (each.getDaysRented() - 3) *1.5;
break;
}
return thisAmount;
}
33
private double amountFor(Rental each)
each and
double thisAmount = 0;
switch (each.getMovie().getPriceCode()) {
thisAmount
case Movie.REGULAR:
thisAmount += 2;
if (each.getDaysRented() > 2)
thisAmount += (each.getDaysRented() - 2) *1.5;
break;
case Movie.NEW_RELAESE:
thisAmount += each.getDaysRented() * 3;
break;
case Movie.CHILDREN:
thisAmount += 1.5;
if (each.getDaysRented() > 3)
thisAmount += (each.getDaysRented() - 3) *1.5;
break;
}
return thisAmount;
} 34
each aRental
private double amountFor(Rental aRental)
double result = 0; thisAmount result
switch (aRental.getMovie().getPriceCode()) {
case Movie.REGULAR:
result += 2;
if (aRental.getDaysRented() > 2)
result += (aRental.getDaysRented() - 2) *1.5;
break;
case Movie.NEW_RELAESE:
result += aRental.getDaysRented() * 3;
break;
case Movie.CHILDREN:
result += 1.5;
if (aRental.getDaysRented() > 3)
result += (aRental.getDaysRented() - 3) *1.5;
break;
}
return result;
} 35
public String statement() {
double totalAmount = 0;
int frequentRenterPoints = 0;
Enumeration rentals = _rentals.elements();
String result = “Rental record for ” + getName() + “\n”;
while (rentals.hasMoreElements()) {
double thisAmount = 0;
Rental each = (Rental) rentals.nextElement();
thisAmount = amountFor(each);
Topic#102
END!
Software Design and Architecture
Topic#103
Refactoring – Example Part V
Move Method
private double amountFor(Rental aRental)
double result = 0;
switch (aRental.getMovie().getPriceCode()) {
amountFor()
case Movie.REGULAR:
result += 2;
uses information
if (aRental.getDaysRented() > 2)
result += (aRental.getDaysRented() - 2) *1.5;
from the Rental
break;
case Movie.NEW_RELAESE:
class, but it does
result += aRental.getDaysRented() * 3;
break;
not use
case Movie.CHILDREN:
result += 1.5;
information from
if (aRental.getDaysRented() > 3)
result += (aRental.getDaysRented() - 3) *1.5;
the Customer
}
break; class where it is
}
return result; currently located.
39
Move method
40
Move method
• let’s also rename the method to getCharge() to
clarify what it is doing.
• as a result, back in customer, we must delete the old
method and change the call to amountFor(each) to
each.getCharge()
• compile and test
41
initially replace the body with the call
remove this method later on and call
directly
private double amountFor(Rental aRental)
return aRental.getCharge();
}
42
while (rentals.hasMoreElements()) {
double thisAmount = 0;
Rental each = (Rental) rentals.nextElement();
//thisAmount = amountFor(each);
thisAmount = each.getCharge();
getCharge() statement()
Topic#103
END!
Software Design and Architecture
Topic#104
Refactoring – Example Part VI
Repeating the process for other areas
frequent renter points
// add frequent renter points
Let’s do the
frequentRenterPoints++;
same thing
// add bonus for two day new release rental
if ((each.getMovie().getPriceCode() == with the
Movie.NEW_RELEASE) &&
each.getDaysRented() > 1)
logic to
frequentRenterPoints++; calculate
// show figures for this rental frequent
result += “\t” + each.getMovie().getTitle() + “\t” +
String.valueOf(thisAmount) + “\n”; renter points
totalAmount += thisAmount;
} // end while 47
frequent renter points
extract method
• each can be parameter
49
public String statement() {
double totalAmount = 0;
int frequentRenterPoints = 0;
Enumeration rentals = _rentals.elements();
String result = “Rental record for ” + getName() + “\n”;
while (rentals.hasMoreElements()) {
double thisAmount = 0;
Rental each = (Rental) rentals.nextElement();
// determine amounts for each line
switch (each.getMovie().getPriceCode()) {
case Movie.REGULAR:
thisAmount += 2;
if (each.getDaysRented() > 2)
thisAmount += (each.getDaysRented() - 2) *1.5;
break;
case Movie.NEW_RELAESE:
thisAmount += each.getDaysRented() * 3;
break;
case Movie.CHILDREN:
thisAmount += 1.5;
if (each.getDaysRented() > 3)
thisAmount += (each.getDaysRented() - 3) *1.5;
break;
}
while (rentals.hasMoreElements()) {
double thisAmount = 0;
Rental each = (Rental) rentals.nextElement();
// determine amounts for each line
thisAmount = each.getCharge();
frequentRenterPoints += each.getFrequentRenterPoints();
Movie
Rental continues to get larger; but
priceCode: int
Rental now has operations that
change it from being a “data holder”
to a useful object.
52
Software Design and Architecture
Topic#104
END!
Software Design and Architecture
Topic#105
Refactoring – Example Part VII
Adding new functionality
Add htmlStatement()
• We are now ready to add the htmlStatement()
function.
55
New Requirements
• It is now anticipated that the store is going
to have more than three initial types of
movies
• as a result of these new classifications, renter
points and charges will vary with each new
movie type.
• as a result, we should probably move the
getCharge() and getFrequentRenterPoints()
methods to the Movie class. 56
Move Methods
58
Software Design and Architecture
Topic#105
END!
Software Design and Architecture
Topic#106
Refactoring – Example Part VIII
Replace Temp with Query
Replace Temp with Query
62
Remove Temp Variables
• let’s replace them with query methods
• little more difficult because they were calculated within a
loop; we have to move the loop to the query methods
a) replace totalAmount with getTotalCharge()
b) replace frequentRentalPoints with
getTotalFrequentPoints()
63
public String statement() {
Enumeration rentals = _rentals.elements();
String result = “Rental record for ” + getName() + “\n”;
while (rentals.hasMoreElements()) {
Rental each = (Rental) rentals.nextElement();
Topic#106
END!
Software Design and Architecture
Topic#107
Refactoring – Example Part IX
Handling Different Types of Objects
How to handle new movies
Movie
getCharge()
• But movies can change type – a New Release Movie can later become
regular movie
• A movie has a particular state: its charge (and its renter points) depend
upon that state; so we can use the state pattern to handle new types of
movies (for now, at least) 69
Replace Type Code with State/Strategy
• We need to get rid of our type code (e.g.
Movie.Children) and replace it with a price object.
• We first modify Movie to get rid of its _priceCode field
and replace it with _priceObject
• This involves changing the customer to make use of the
setPriceCode() method; before it was setting priceCode
directly.
• We also have to change getPriceCode and setPriceCode to
access the Price Object
• We of course need to create Price and its subclasses 70
Move Method
71
Replace Conditional with Polymorphism
72
How to handle new movies
Movie 1 Price
getCharge() getCharge()
73
Handle renter points
74
We’re done!
• We have added new functionality, changed “data
holders” to “objects” and made it easy to add
new types of movies with special charges and
frequent rental points.
75
Software Design and Architecture
Topic#107
END!
Software Design and Architecture
Topic#108
Refactoring – Managing Refactoring
Why Developers are Reluctant to Refactor
•Lack of understanding
•Short-term focus
•Not paid for overhead tasks like
refactoring
•Fear of breaking current program
Managing Refactoring!
• Manager’s point-of-view
• If my programmers spend time “cleaning up
the code” then that’s less time implementing
required functionality (and my schedule is
slipping as it is!)
• To address this concern
• Refactoring needs to be systematic,
incremental, and safe. 79
When should you refactor?
• The Rule of Three
• Three strikes and you refactor
• refers to duplication of code
• Refactor when you add functionality
• do it before you add the new function to make it easier
to add the function
• or do it after to clean up the code after the function is
added
• Refactor when you need to fix a bug
• Refactor as you do a code review 80
Software Design and Architecture
Topic#108
END!
Software Design and Architecture
Topic#109
Refactoring – Problems with Refactoring
Problems with Refactoring
•Taken too far, refactoring can lead to
incessant tinkering with the code, trying
to make it perfect
83
Problems with Refactoring
•Business applications are often tightly
coupled to underlying databases
• code is easy to change; databases are not
84
Problems with Refactoring
•Changing Interfaces
• Some refactorings require that interfaces
be changed
• if you own all the calling code, no problem
• if not, the interface is “published” and can’t
change
85
Problems with Refactoring
•Design Changes that are difficult to
refactor
• Better to redo than to refactor
• Software Engineers should have
“courage”!
86
Software Design and Architecture
Topic#109
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 110 – 118
MVC Architecture
Software Design and Architecture
Topic#110
MVC – Challenges of Interactive Application
Questions
• How to reuse code among different
interactive applications offering the same
service?
• How to simultaneously create multiple user
interfaces for same service?
Questions
• Normal vs. Slide sorter
• Shortcuts vs. menus vs. buttons
Questions
• How to simultaneously create multiple user interfaces for same
service on different computers?
• Facebook, email
Questions
• How to simultaneously create distributed user interfaces
• multiple complete user interfaces for different users on different computers
• Single user-interface on large computer controlled by multiple mobile devices
Software Design and Architecture
Topic#110
END!
Software Design and Architecture
Topic#111
MVC – Example Part I
Requirements
Example: Counter
Can add
arbitrary Different
positive/negative user
value to an
integer interfaces
Console-based Input and Output
Console-based Input and JOption Output
Console-based Input,Output and JOption Output
Software Design and Architecture
Topic#111
END!
Software Design and Architecture
Topic#112
MVC – Example Part II
Monolithic Console Implementation
public class MonolithicConsoleUI {
public static void main(String[] args) {
int counter = 0;
while (true) { Output
System.out.println("Counter: " + counter);
int nextInput = Console.readInt();
if (nextInput == 0) break; Input
counter += nextInput;
}
}
}
Software Design and Architecture
Topic#112
END!
Software Design and Architecture
Topic#113
MVC – Example Part III
Monolithic Mixed UI Implementation
import javax.swing.JOptionPane;
public class ConsoleUI {
public static void main(String[] args) {
int counter = 0;
Output
while (true) {
JOptionPane.showMessageDialog(
null, “Counter: ” + counter);
int nextInput = Console.readInt();
if (nextInput == 0) break; Input
counter += nextInput;
}
}
}
Software Design and Architecture
Topic#113
END!
Software Design and Architecture
Topic#114
MVC – Example Part IV
Models and Interactors
Multiple UIs?
UI Code Interactor
Arbitrary UI unaware
methods
Topic#114
END!
Software Design and Architecture
Topic#115
MVC – Example Part V
Using Models and Interactors
public class ConsoleUI {
public static void main(String[] args) {
int counter = 0;
while (true) {
System.out.println("Counter: " + counter);
int nextInput = Console.readInt();
if (nextInput == 0) break;
counter += nextInput;
}
}
}
Counter Model
public class ACounter implements Counter { No
int counter = 0; input/output
public void add (int amount) {
counter += amount; Any class that can
} be attached to a
user-interface but
public int getValue() {
is oblivious to the
return counter; user-interface is
} referred to as a
} model.
Console Interactor
public class AConsoleUIInteractor implements CounterInteractor {
UI Implementation is
I/O Code is Duplicated
now monolithic
Software Design and Architecture
Topic#115
END!
Software Design and Architecture
Topic#116
MVC – Example Part VI
Drawbacks of Monolithic UI
Drawbacks of Monolithic UI
Duplicated Input Code AConsoleUI
Counter AMixedUI
Duplicated Output
Code AMultipleUI
Software Design and Architecture
Topic#116
END!
Software Design and Architecture
Topic#117
MVC – Example Part VII
MVC Architectural Pattern
MVC Pattern
Performs Output
Performs Input Controller View
Computation Code
Performs Output
Performs Input
Controller View
Performs Output
Performs Input Controller View
Performs Output
Performs Input Controller View
View
Multiple Views and Controllers
Controller 1 View 1
Controller 3 View 3
Topic#117
END!
Software Design and Architecture
Topic#118
MVC – Example Part VIII
MVC and Observer
Syncing Controllers & View
Controller 1 View 1
Controller 3 View 3
Controller 4 View 4
In Http-based “MVC” a single view and controller exists in the browser and the
model in the server. A Model cannot initiate actions in the browser so the
controller directly communicates with the view
Observer Pattern
Observable Observers
View 1
Model View 2
Changed model
notifies views View 3
View 4
MVC Pattern (Review)
Performs Output
Performs Input
Controller View
Performs Output
Performs Input
Notification Method View
Controller
Observer
Registration
Method
Complete MVC
Model Connection
Performs Output
Method
Performs Input
Notification Method View
Controller
Observer
Registration
Method
Software Design and Architecture
Topic#118
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 119 – 127
Software Architecture - Overview
Software Design and Architecture
Topic#119
What is software architecture?
What is software architecture
The word “architecture”
means many different
things to many different
people
Software systems are constructed to
satisfy organizations’ business goals
The architecture is a bridge between
those (often abstract) business goals
and the final (concrete) resulting system.
Topic#119
END!
Software Design and Architecture
Topic#120
Categories of structures in Architectural Design
Categories of Structures in Architectural
Design
•Three categories
Categories of Structures in Architectural
Design
• Static Structures
• Implementation units or modules
• Dynamic Structures
• component-and-connector (C&C) structures –
components are runtime entities
• Deployment Structures
• aka allocation structures
•Play an important role in the
design, documentation, and
analysis of architectures
Software Design and Architecture
Topic#120
END!
Software Design and Architecture
Topic#121
Static Software Structures - Modules
Implementation units or modules
• Static structures
• focus on the way the system’s functionality is divided up
and assigned to implementation teams.
• Assigned specific computational responsibilities
• Basis of work assignments for programming teams
• (Team A works on the database, Team B works on the
business rules, Team C works on the user interface, etc.)
Implementation units or modules
• In large projects, these elements (modules)
are subdivided for assignment to subteams.
• For example, the database for a large
enterprise resource planning (ERP)
implementation might be so complex that
its implementation is split into many parts.
• aka Module Decomposition Structure
• captures that decomposition
Implementation units or modules
•Class Diagrams
• Kind of module structure emerges as an
output of object-oriented analysis and
design
•Layered Structure
• Modules aggregated (organized) into layers
Software Design and Architecture
Topic#121
END!
Software Design and Architecture
Topic#122
Component-and-Connector and Allocation Structures
Component-and-Connector (C&C) Structures
•Runtime structures
•Component
•Focus on the way the elements
interact with each other at runtime to
carry out the system’s functions.
Component-and-Connector (C&C) Structures
•For example the system to be built as a set
of services would include:
• the service – made up of the programs in
various implementation units
• the infrastructure they interact with
• the synchronization and interaction relations
among them
Allocation Structures
Topic#122
END!
Software Design and Architecture
Topic#123
Quality Attributes
Architectural Structures
Topic#123
END!
Software Design and Architecture
Topic#124
What should not be included in it?
Software Architecture
• an architecture is an abstraction of a system that
selects certain details and suppresses others.
• The architecture specifically omits certain
information about elements that is not useful for
reasoning about the system
• information that has no ramifications outside of a
single element
Software Architecture
Topic#124
END!
Software Design and Architecture
Topic#125
Difference between Architecture and Representation of
the Architecture
Every Software System Has a Software
Architecture
•Every system can be shown to comprise
elements and relations among them to
support some type of reasoning.
• In the most trivial case, a system is itself a
single element—an uninteresting and
probably non-useful architecture, but an
architecture nevertheless.
Even though every system has an
architecture, it does not necessarily
follow that the architecture is
known to anyone
Because an architecture can exist
independently of its description or
specification, this raises the importance of
architecture documentation
Software Design and Architecture
Topic#125
END!
Software Design and Architecture
Topic#126
Difference between Software, System, and Enterprise
Architectures
• System and enterprise architectures share a
great deal with software architectures
• All can be designed, evaluated, and
documented
• all answer to requirements
• all are intended to satisfy stakeholders
• all consist of structures, which in turn consist
of elements and relationships
• Each has its own specialized vocabulary and
techniques
System and Enterprise Architectures
Topic#126
END!
Software Design and Architecture
Topic#127
Architectural Views
Different views of the human body:
the skeletal, the vascular, and the X-ray
Although these
views are pictured
differently and
have very different
properties, all are
inherently related,
interconnected
Different views of the human body:
the skeletal, the vascular, and the X-ray
Together they
describe the
architecture of
the human
body
Software Architectural Views
Topic#127
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 128 – 138
Software Architecture – Overview - Part II
Software Design and Architecture
Topic#128
4+1 View Model of Software Architecture
“4+1 view model”
• Philippe Kruchten
• leader of RUP development team in Rational
corp. (now owned by IBM)
• Valuable experiences in industry (Telecom, Air
traffic control system) which he used them for
confirmation of his model
3
Problem
• Various stakeholders of software system:
• end-user, developers, system engineers, project
managers
• Arch. documents over-emphasize an aspect of
development (i.e. team organization)
• do not address the concerns of all stakeholders
• Software engineers struggled to represent more
on one blueprint, and so arch.
• documents contain complex diagrams 4
Solution
Scenarios
6
Logical View
(Object-oriented Decomposition)
Viewer: End-user
considers:
• Functional requirements
• What the system should provide in terms of
services to its users.
7
Process View
(The process decomposition)
viewer: Integrators
considers:
• Non - functional requirements
• (concurrency, performance, scalability)
8
Development View
(Subsystem decomposition)
Basis of a line of product
Viewer: Programmers and Software Managers
considers:
• software module organization
• (Hierarchy of layers, software management,
reuse, constraints of tools) 9
Physical View
10
Scenarios
11
Correspondence between views
12
Software Design and Architecture
Topic#128
END!
Software Design and Architecture
Topic#129
Module Structures
The Three Categories of Structures in
Architectural Design
• Static Structures
• Module Structures
• Dynamic Structures
• component-and-connector (C&C) structures –
components are runtime entities
• Deployment Structures
• aka allocation structures
Module Structures
• Embody decisions as to how the system is to be
structured as a set of code or data units that have to
be constructed or procured.
• In any module structure, the elements are modules of
some kind (perhaps classes, or layers, or merely
divisions of functionality, all of which are units of
implementation).
Module Structures
Topic#129
END!
Software Design and Architecture
Topic#130
Component and Connector Structures
Component-and-connector Structures
• Embody decisions as to how the system is to be
structured as a set of elements that have runtime
behavior (components) and interactions (connectors)
• The elements are runtime components
• which are the principal units of computation
• services, peers, clients, servers, filters, etc
• connectors - communication vehicles among components
• call-return, process synchronization operators, pipes, etc
Component-and-connector Structures
• Component-and-connector views help us answer
questions such as these:
• What are the major executing components and how do
they interact at runtime?
• What are the major shared data stores?
• Which parts of the system are replicated?
• How does data progress through the system?
• What parts of the system can run in parallel?
• Can the system’s structure change as it executes and, if
so, how?
Component-and-connector Structures
• component-and-connector views are crucially
important for asking questions about the system’s
runtime properties
• performance, security, availability, and more
Software Design and Architecture
Topic#130
END!
Software Design and Architecture
Topic#131
Allocation Structures
Allocation Structures
• Embody decisions as to how the system will relate
to non software structures in its environment
• CPUs, file systems, networks, development teams, etc.
• These structures show the relationship between
the software elements and elements in one or
more external environments in which the software
is created and executed.
Allocation Structures
• Allocation views help us answer questions such as
these:
• What processor does each software element execute on?
• In what directories or files is each element stored during
development, testing, and system building?
• What is the assignment of each software element to
development teams?
Useful for
Topic#131
END!
Software Design and Architecture
Topic#132
Structures and Quality Attributes
Putting it all together
• Static Structures
• Module Structures
• Dynamic Structures
• component-and-connector (C&C) structures –
components are runtime entities
• Deployment Structures
• aka allocation structures
•Each structure provides a
perspective for reasoning about
some of the relevant quality
attributes.
•For example:
• The module “uses” structure, which
embodies what modules use what other
modules, is strongly tied to the ease with
which a system can be extended or
contracted.
• For example:
• The concurrency structure, which embodies
parallelism within the system, is strongly tied to the
ease with which a system can be made free of
deadlock and performance bottlenecks.
•For example:
• The deployment structure is strongly tied
to the achievement of performance,
availability, and security goals.
• Each structure provides the architect with a
different insight into the design (that is,
each structure can be analyzed for its ability
to deliver a quality attribute).
• Each structure presents the architect with
an engineering leverage point
• By designing the structures appropriately, the
desired quality attributes emerge.
Software Design and Architecture
Topic#132
END!
Software Design and Architecture
Topic#133
Relating Structures to Each Other
Relating Structures to Each Other
Topic#133
END!
Software Design and Architecture
Topic#134
Choosing an Appropriate Structure
Degree of Rigor
Topic#134
END!
Software Design and Architecture
Topic#135
Architectural Patterns – Overview
• In some cases, architectural elements are
composed in ways that solve particular
problems.
• The compositions have been found useful over
time, and over many different domains, and so
they have been documented and disseminated.
• These compositions of architectural elements,
called architectural patterns, provide packaged
strategies for solving some of the problems
facing a system.
•An architectural pattern delineates the
element types and their forms of
interaction used in solving the problem.
•Patterns can be characterized according
to the type of architectural elements
they use
Some Examples
• Module Patterns
• Layered Pattern
• Component-and-connector type pattern
• Shared Data (or repository) Pattern
• Client-Server Pattern
• Allocation Patterns
• Multi-tier pattern
• Competence center and platform center
Layered Pattern
• Module type pattern
• When the uses relation among software elements is strictly unidirectional, a
system of layers emerges.
• A layer is a coherent set of related functionality.
• In a strictly layered structure, a layer can only use the services of the layer
immediately below it.
• Many variations of this pattern, lessening the structural restriction, occur in
practice.
• Layers are often designed as abstractions (virtual machines) that hide
implementation specifics below from the layers above, engendering portability
Shared Data (or repository) Pattern
• Component-and-connector type pattern
• comprises components and connectors that create, store, and access
persistent data.
• The repository usually takes the form of a database.
• The connectors are protocols for managing the data, such as SQL.
Client-Server Pattern
• Component-and-connector type pattern
• The components are the clients and the servers, and the connectors
are protocols and messages they share among each other to carry out
the system’s work.
Multi-tier Pattern
• Allocation pattern
• Describes how to distribute and allocate the components of a system
in distinct subsets of hardware and software, connected by some
communication medium.
• This pattern specializes the generic deployment (software-to-
hardware allocation) structure.
Competence center and platform
• Allocation pattern
• specialize a software system’s work assignment structure.
• In competence center, work is allocated to sites depending on the
technical or domain expertise located at a site.
• For example, user-interface design is done at a site where usability
engineering experts are located.
• In platform, one site is tasked with developing reusable core assets of
a software product line, and other sites develop applications that use
the core assets.
Software Design and Architecture
Topic#135
END!
Software Design and Architecture
Topic#136
What makes a good architecture?
• No such thing as an inherently good or bad
architecture
• Is it fit for some purpose?
• A three-tier layered service-oriented
architecture may be the right thing for a large
enterprise’s web-based B2B system but
completely wrong for an avionics application.
• An architecture carefully crafted to achieve high
modifiability does not make sense for a
throwaway prototype (and vice versa!).
• Architectures can in fact be evaluated—but only
in the context of specific stated goals
• There are rules of thumb that should be
followed when designing most architectures
• Failure to apply any of these does not
automatically mean that the architecture will be
fatally flawed, but it should at least serve as a
warning sign that should be investigated.
Recommendation
•process recommendations
•product (or structural)
recommendations
Software Design and Architecture
Topic#136
END!
Software Design and Architecture
Topic#137
Process Recommendations
Process Recommendations - 1
• The architecture should be the product of a single
architect or a small group of architects with an
identified technical leader.
• This approach gives the architecture its conceptual
integrity and technical consistency.
• This recommendation holds for Agile and open source
projects as well as “traditional” ones.
• There should be a strong connection between the
architect(s) and the development team, to avoid ivory
tower designs that are impractical.
Process Recommendations - 2
Topic#137
END!
Software Design and Architecture
Topic#138
Product Recommendations
Structural Recommendations - 1
• The architecture should feature well-defined modules whose
functional responsibilities are assigned on the principles of
information hiding and separation of concerns.
• The information-hiding modules should encapsulate things likely to
change, thus insulating the software from the effects of those
changes.
• Each module should have a well-defined interface that
encapsulates or “hides” the changeable aspects from other
software that uses its facilities.
• These interfaces should allow their respective development teams
to work largely independently of each other.
Structural Recommendations - 2
Topic#138
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 139 – 148
Architecture Meta-Frame – Part I
Software Design and Architecture
Topic#139
Architectural Drivers
considerations that need to be
made for the software system
that are architecturally
significant.
They drive and guide the design
of the software architecture.
Architectural drivers describe
what you are doing and why you
are doing it.
Software architecture design
satisfies architectural drivers.
•Architectural drivers are inputs into
the design process, and include:
•Design objectives
•Primary functional requirements
•Quality attribute scenarios
•Constraints
•Architectural concerns
Software Design and Architecture
Topic#139
END!
Software Design and Architecture
Topic#140
The Architecture Meta-Frame
considerations that need to be
made for the software system
that are architecturally
significant.
The Architecture Meta-Frame
Scenarios.
Application scenarios tie architecture
solutions to the real-world scenarios that
impact your application design.
Scenarios - Examples
your application may map to an Internet Web
application scenario, which has unique
architecture solutions compared to a mobile
client application.
Quality attributes.
Quality attributes represent cross-cutting
concerns that apply across application types,
and should be considered regardless of
architecture style.
Quality attributes - Examples
Security, performance, maintainability,
reusability, etc.
Requirements and constraints.
Requirements and constraints narrow the
range of possible solutions for your
application architecture problems
Application types.
Application types categorize the major
application technology stacks.
e.g. Mobile, Rich Internet Application, Web
App, Service App, etc
Architecture styles.
An architectural style is a collection of principles
that shapes the design of your application.
Many of these styles overlap and can be used in
combination.
Architecture styles.
Architectural styles tend to be tied both to
the application type and to the point in time
in which the application was developed.
Architecture frame.
The architecture frame is a collection of
hotspots that you can use to analyze your
application architecture.
Architecture frame.
This helps you to turn core features such as
caching, data access, validation, and
workflow into actions.
Software Design and Architecture
Topic#140
END!
Software Design and Architecture
Topic#141
The Architecture Meta-Frame
Quality Attributes: Introduction
•A quality attribute (QA) is a measurable
or testable property of a system that is
used to indicate how well the system
satisfies the needs of its stakeholders.
Topic#141
END!
Software Design and Architecture
Topic#142
The Architecture Meta-Frame
Architecturally Significant Quality Attributes
•architecture provides the mapping of a
system’s functionality onto software
structures that determines the
architecture’s support for qualities
Topic#142
END!
Software Design and Architecture
Topic#143
The Architecture Meta-Frame
Guidelines for Quality Attributes
• When designing to accommodate quality
attributes, consider the following guidelines:
• Quality attributes are system properties that
are separate from the functionality of the
system.
• From a technical perspective, implementing
quality attributes can differentiate a good
system from a bad one.
• There are two types of quality attributes:
• those that are measured at run time, and
• those that can only be estimated through
inspection.
• Analyze the tradeoffs between quality
attributes.
• Questions you should ask when considering
quality attributes include:
• What are the key quality attributes required
for your application? Identify them as part of
the design process.
• What are the key requirements for addressing
these attributes? Are they actually
quantifiable?
• What are the acceptance criteria that will
indicate that you have met the requirements?
Software Design and Architecture
Topic#143
END!
Software Design and Architecture
Topic#144
The Architecture Meta-Frame
Quality Attributes – Description
Software Design and Architecture
Topic#144
END!
Software Design and Architecture
Topic#145
The Architecture Meta-Frame
Requirements and Constraints
•Constraints
• a design decision with zero degrees of
freedom
• external factors (such as not being able to
train the staff in a new language, or having a
business agreement with a software
supplier, or pushing business goals of service
interoperability) have led those in power to
dictate these design outcomes.
Software Design and Architecture
Topic#145
END!
Software Design and Architecture
Topic#146
The Architecture Meta-Frame
Application Types
Application Types
Topic#146
END!
Software Design and Architecture
Topic#147
The Architecture Meta-Frame
Application Types and Deployment Strategy
Deployment Strategy
Topic#147
END!
Software Design and Architecture
Topic#148
The Architecture Meta-Frame
Application Types – Description
Software Design and Architecture
Topic#148
END!
Software Design and Architecture
Topic#149
The Architecture Meta-Frame
Architecture Styles
Architectural Style
Topic#149
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 150 – 164
Architecture Meta-Frame – Part II
Software Design and Architecture
Topic#150
The Architecture Meta-Frame
Architecture Frame – Part I – Cross-Cutting Concerns
Architecture frame
•The architecture frame is a collection of
hotspots that you can use to analyze
your application architecture.
Topic#150
END!
Software Design and Architecture
Topic#151
The Architecture Meta-Frame
Architecture Frame – Part II – Key Cross-Cutting Concerns
Key Cross-Cutting Concerns - Authentication
and authorization
•allow one to identify the users of an
application with confidence, and to
determine the resources and
operations to which they should
have access.
Key Cross-Cutting Concerns
• Authentication.
• Determine how to authenticate your
users and pass authenticated identities
across the layers.
Key Cross-Cutting Concerns
• Authorization
• Ensure proper authorization with
appropriate granularity within each
layer, and across trust boundaries.
Key Cross-Cutting Concerns - Caching
Topic#151
END!
Software Design and Architecture
Topic#152
The Architecture Meta-Frame
Topic#152
END!
Software Design and Architecture
Topic#153
The Architecture Meta-Frame
Topic#153
END!
Software Design and Architecture
Topic#154
The Architecture Meta-Frame
Topic#154
END!
Software Design and Architecture
Topic#155
The Architecture Meta-Frame
Topic#155
END!
Software Design and Architecture
Topic#156
The Architecture Meta-Frame
Topic#156
END!
Software Design and Architecture
Topic#157
The Architecture Meta-Frame
Topic#157
END!
Software Design and Architecture
Topic#158
Agility and Architecture Design
•Modern thinking on architecture
assumes that your design will evolve
over time and that you cannot know
everything you need to know up front in
order to fully architect your system.
•Your design will generally need to evolve
during the implementation stages of the
application as you learn more, and as
you test the design against real-world
requirements.
•Create your architecture with this
evolution in mind so that it will be agile
in terms of adapting to requirements
that are not fully known at the start of
the design process.
•Consider the following questions as you
create an architectural design with agility in
mind:
• What are the foundational parts of the
architecture that represent the greatest risk if
you get them wrong?
• What are the parts of the architecture that are
most likely to change, or whose design you
can delay until later with little impact?
• What are your key assumptions, and how will
you test them?
• What conditions may require you to refactor
the design?
• There will be aspects of your design that you
must fix early in the process, which may
represent significant cost if redesign is
required. Identify these areas quickly and
invest the time necessary to get them right.
Software Design and Architecture
Topic#158
END!
Software Design and Architecture
Topic#159
Key Architecture Principles
Key Architecture Principles
Topic#159
END!
Software Design and Architecture
Topic#160
Incremental and Iterative
Approach to Architectural Design
Incremental and Iterative Approach to
Architecture
•Consider using an incremental and iterative
approach to refining your architecture.
•Do not try to get it all right the first time—
design just as much as you can in order to
start testing the design against
requirements and assumptions.
•Iteratively add details to the design over
multiple passes to make sure that you get
the big decisions right first, and then focus
on the details.
• A common pitfall is to dive into the details
too quickly and get the big decisions wrong
by making incorrect assumptions, or by
failing to evaluate your architecture
effectively.
Software Design and Architecture
Topic#160
END!
Software Design and Architecture
Topic#161
Baseline and Candidate
Architectures
Baseline Architecture
Topic#161
END!
Software Design and Architecture
Topic#162
Architectural Spikes
Architectural Spikes
Topic#162
END!
Software Design and Architecture
Topic#163
Architecturally Significant Use
Cases
Architecturally Significant Use Cases
Topic#163
END!
Software Design and Architecture
Topic#164
Reference Application
Architecture
•Represents a canonical view of a typical
application architecture, using a layered
style to separate functional areas into
separate layers.
•The reference application architecture
demonstrates how a typical application
might interact with its users, external
systems, data sources, and services.
•The reference application architecture also
shows how cross-cutting concerns such as
security and communication impact all of
the layers in your design, and must be
designed with the entire application in mind.
Microsoft’s
reference
application
architecture
Software Design and Architecture
Topic#164
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 165 – 184
Software Architecture Patterns
Software Design and Architecture
Topic#165
Software Architecture Patterns - Introduction
Software Architecture Patterns
aka architecture styles
•A software architecture pattern is a
solution to a recurring problem that is
well understood, in a particular context.
•Each pattern consists of a context, a
problem, and a solution.
Software Architecture Patterns
•The problem may be to overcome some
challenge, take advantage of some
opportunity, or to satisfy one or more
quality attributes.
•Patterns codify knowledge and
experience into a solution that we can
reuse.
Software Architecture Patterns
•Using patterns simplifies design and
allows us to gain the benefits of using a
solution that is proven to solve a
particular design problem.
Software Architecture Patterns
•When working with others who are
familiar with patterns, referencing one
of them provides a shorthand with
which to reference a solution, without
having to explain all its details.
•As a result, they are useful during
discussions to communicate ideas.
Software Architecture Patterns
•Each pattern has its own characteristics,
strengths, and weaknesses.
Software Design and Architecture
Topic#165
END!
Software Design and Architecture
Topic#166
Difference between Software Architecture Patterns and
Design Patterns
•Software architecture patterns are
similar to design patterns, except that
they are broader in scope and are
applied at the architecture level.
•Architecture patterns tend to be more
coarse-grained and focus on
architectural problems, while design
patterns are more fine-grained and solve
problems that occur during
implementation.
•A software architecture pattern provides
a high-level structure and behavior for
software systems.
•It is a grouping of design decisions that
have been repeated and used
successfully for a given context.
•They address and satisfy architectural
drivers and as a result, the ones that we
decide to use can really shape the
characteristics and behavior of the
architecture.
•Software architecture patterns provide
the structure and main components of
the software system being built.
•They introduce design constraints, which
reduce complexity and help to prevent
incorrect decisions.
•When a software architecture pattern is
followed consistently during design, we
can anticipate the properties that the
software system will exhibit.
•This allows us to consider whether a
design will satisfy the requirements and
quality attributes of the system.
•Software architecture patterns can be
applied to the entire software system or
to one of the subsystems.
•Consequently, more than one software
architecture pattern can be used in a
single software system. These patterns
can be combined to solve problems.
Software Design and Architecture
Topic#166
END!
Software Design and Architecture
Topic#167
Types of Architecture Patterns
The Three Categories of Structures in
Architectural Design
• Static Structures
• Module Structures
• Dynamic Structures
• component-and-connector (C&C) structures –
components are runtime entities
• Deployment Structures
• aka allocation structures
The Three Categories of Structures in
Architectural Design
• Static Structures
• Module Structures
• assigned areas of functional responsibility
• how the system is to be structured as a set of
code or data units that have to be constructed or
procured
The Three Categories of Structures in
Architectural Design
• component-and-connector (C&C) structures –
components are runtime entities
• how the system is to be structured as a set of
elements that have runtime behavior (components)
and interactions (connectors)
• components - the principal units of computation
• connectors - communication vehicles among
components
The Three Categories of Structures in
Architectural Design
• Deployment Structures
• how the system will relate to non-software
structures in its environment
• show the relationship between the software
elements and elements in one or more
external environments in which the software is
created and executed
•Patterns can be categorized by the
dominant type of elements that they show
• module patterns show modules,
• component-and-connector (C&C) patterns
show components and connectors
• allocation patterns show a combination of
software elements (modules, components,
connectors) and non-software elements.
•Most published patterns are C&C patterns,
but there are module patterns and
allocation patterns as well.
Software Design and Architecture
Topic#167
END!
Software Design and Architecture
Topic#168
Module Patterns
Layered Pattern – I: Introduction
•Context:
• All complex systems experience the need to
develop and evolve portions of the system
independently.
• For this reason the developers of the system
need a clear and well-documented
separation of concerns, so that modules of
the system may be independently developed
and maintained.
•Problem:
• The software needs to be segmented in such
a way that the modules can be developed
and evolved separately with little
interaction among the parts, supporting
portability, modifiability, and reuse.
•Solution:
• the layered pattern divides the software into
units called layers.
• Each layer is a grouping of modules that
offers a cohesive set of services.
•one of the most common techniques.
•In a layered architecture, the software
application is divided into various
horizontal layers, with each layer located
on top of a lower layer.
•Each layer is dependent on one or more
layers below it (depending on whether the
layers are open or closed), but is
independent of the layers above it.
Software Design and Architecture
Topic#168
END!
Software Design and Architecture
Topic#169
Module Patterns
Layered Pattern – II: Open vs Closed Layers
•Open versus closed layers
• With a closed layer, requests that are flowing
down the stack from the layer above must go
through it and cannot bypass it.
• Open versus closed layers
• Example:
• three-layer architecture with
presentation, business, and data Presentation
layers
Business
• if the business layer is closed, the
presentation layer must send all
Data
requests to the business layer and
cannot bypass it to send a
request directly to the data layer.
•Closed layers provide layers of isolation,
which makes code easier to change, write,
and understand.
•This makes the layers independent of each
other, such that changes made to one layer
of the application will not affect
components in the other layers.
•If the layers are open, this increases
complexity.
•Maintainability is lowered because
multiple layers can now call into another
layer, increasing the number of
dependencies and making changes more
difficult.
•unnecessary traffic can result when each
layer must be passed even if one or more
of them is just passing requests on to the
next layer.
•added a shared services layer
between the business and
data layers.
Presentation
• may contain reusable
components needed by Business
multiple components in the
business layer. Shared-Service
• placed it below the business
layer so that only the business Data
layer has access to it.
•all requests from the business
layer to the data layerAllmust
quiz
Data
•If the shared services layer
was made open (aka layer
bridging), requests to the
Presentation
data layer can be made
directly from the business Business
layer.
Shared-Service
Data
•there are advantages to
closed layers and achieving
layers of isolation.
Presentation
•However, it might be
appropriate to open a layer. Business
•It is not necessary to make all
Shared-Service
of the layers open or closed.
•You may selectively choose Data
which layers, if any, are open.
Software Design and Architecture
Topic#169
END!
Software Design and Architecture
Topic#170
Module Patterns
Layered Pattern – III: Tiers vs Layers
• Layers – Logical separation
• Tiers – Physical separation
• When partitioning
application logic, layers are a
way to organize functionality Presentation
and components.
• For example, in a three- Business
layered architecture, the logic
may be separated into Data
presentation, business,
and data layers.
•When a software architecture is
organized into more than one layer, it is
known as a multi-layer architecture.
• Different layers do not necessarily have to
be located on different physical machines.
• It is possible to have multiple layers on the
same machine.
•Tiers concern themselves with the
physical location of the functionality and
components.
• A three-tiered architecture
with presentation, business,
and data tiers implies that
those three tiers have been
physically deployed to three
separate machines and are
each running on those
separate machines.
•When a software architecture is
partitioned into multiple tiers, it is
known as a multi-tier architecture.
Software Design and Architecture
Topic#170
END!
Software Design and Architecture
Topic#171
Module Patterns
Layered Pattern – IV: Advantages of layered architectures
• This pattern reduces complexity by
achieving a Separation of Concerns (SoC).
• Each layer is independent and you can
understand it on its own without the other
layers.
• Complexity can be abstracted away in a
layered application, allowing us to deal with
more complex problems.
• Dependencies between layers can be
minimized in a layered architecture, which
further reduces complexity.
• For example, the presentation layer does not
need to depend directly on the data layer and
the business layer does not depend on the
presentation layer.
• Minimizing dependencies also allows you to
substitute implementations for a particular
layer without affecting the other layers.
• they can make development easier.
• The pattern is pervasive and well known to
many developers, which makes using it easy
for the development team.
• Due to the way that the architecture separates
the application logic, it matches up well with
how many organizations hire their resources
and allocate tasks during a project.
• Each layer requires a particular skill set and
suitable resources can be assigned to work on
each layer.
• For example, UI developers for the presentation
layer, and backend developers for the
business and data layers.
• This architecture pattern increases the
testability quality attribute of software
applications.
• Partitioning the application into layers and
using interfaces for the interaction between
layers allows us to isolate a layer for testing
and either mock or stub the other layers.
• For example, you can perform unit testing on
classes in your business layer without the
presentation and data layers.
• The business layer is not dependent on
the presentation layer and the data
layer can be mocked or stubbed.
• Applications using a layered architecture
may have higher levels of reusability if more
than one application can reuse the same
layer.
• For example, if multiple applications target the
same business and/or data layers, those
layers are reusable.
• When an application using a layered
architecture is deployed to different tiers,
there are additional benefits:
• increased scalability as more hardware can be added
to each tier
• greater levels of availability when multiple machines
are used per layer.
• Uptime is increased because, if a hardware failure takes
place in a layer, other machines can take over.
• Having separate tiers enhances security as firewalls
can be placed in between the various layers.
• If a layer can be reused for multiple applications, it
means that the physical tier can be reused as well.
Software Design and Architecture
Topic#171
END!
Software Design and Architecture
Topic#172
Module Patterns
Layered Pattern – V: Disadvantages of layered architectures
• Although the layers can be designed to be
independent, a requirement change may require
changes in multiple layers.
• This type of coupling lowers the overall agility of the
software application.
• For example, adding a new field will require changes to
multiple layers: the presentation layer so that it can be
displayed, the business layer so that it can be
validated/saved/processed, and the data layer
because it will need to be added to the database.
• This can complicate deployment because, even for a
change such as this, an application may require
multiple parts (or even the entire application) to be
deployed.
• more code will be necessary for layered applications.
• This is to provide the interfaces and other logic that are
necessary for the communication between the
multiple layers.
• Development teams have to be diligent about placing
code in the correct layer so as not to leak logic to a
layer that belongs in another layer.
• Examples of this include placing business logic in the
presentation layer or putting data-access logic in
the business layer.
• there can be inefficiencies in having a request go
through multiple layers.
• moving from one layer to another sometimes
requires data representations to be transformed.
• One way to mitigate this disadvantage is to allow
some layers to be open but this should only be done
if it is appropriate to open a layer.
• disadvantages to layered architectures when they are
deployed to multiple tiers:
• when layers are deployed to separate physical tiers,
there is an additional performance cost.
• With modern hardware, this cost may be small but
it still won't be faster than an application that
runs on a single machine.
• There is a greater monetary cost associated with having
a multi-tier architecture.
• The more machines are used for the application, the greater
the overall cost.
• Unless the hosting of the software application is handled by a
cloud provider or has otherwise been outsourced, an
internal team will be needed to manage the physical
hardware of a multi-tier application.
Software Design and Architecture
Topic#172
END!
Software Design and Architecture
Topic#173
Module Patterns
Layered Pattern – VI: Client-server architecture (two-tier architecture)
• client-server architecture, also
known as a two-tier architecture
• distributed application
• clients and servers communicate with
each other directly.
• A client requests some resource or
calls some service provided by a
server and the server responds to the
requests of clients.
• There can be multiple clients
connected to a single server
• The Client part of the application
contains the user interface code and
the Server contains the database
• The majority of application logic in a
client-server architecture is located
on the server, but some of it could
also be located in the client.
• The application logic located on the
server might exist in software
components, in the database, or
both.
• When the client contains a significant
portion of the logic and is handling a
large share of the workload, it is
known as a thick, or fat, client.
• When the server is doing that instead,
the client is known as a thin client.
• In some client-server applications, the
business logic is spread out between
the client and the server.
• If consistency isn't applied, it can
make it difficult to always know
where a particular piece of logic is
located.
• If a team isn't diligent, business logic
might be duplicated on the client and
the server.
• There may be instances in which the
same piece of logic is needed on both
the client and the server.
• For example, there may be
business logic needed by the user
interface to validate a piece of
data prior to submitting the data
to the server.
• The server may need this same
business logic because it also
needs to perform this validation.
• While centralizing this logic may
require additional communication
between the client and the server,
the alternative (duplication)
lowers maintainability.
• If the business logic were to
change, it would have to be
modified in multiple places.
Software Design and Architecture
Topic#173
END!
Software Design and Architecture
Topic#174
Module Patterns
Layered Pattern – VII: n-tier architecture
• also known as a multitier architecture
• there are multiple tiers in the
architecture.
• One of the most widely-used variations
of this type of layered architecture is
the three-tier architecture.
• The three-tier architecture separates
logic into presentation, business, and
data layers:
• Presentation tier
• The presentation tier provides
functionality for the application's UI.
• It should provide an appealing visual
design as it is the part of the
application that users interact with
and see.
• Data is presented to the user and
input is received from users in this
tier.
• Presentation tier
• Aspects of the usability quality
attribute should be the concern of the
presentation tier.
• Software architects should strive to
design thin clients that minimize the
amount of logic that exists in the
presentation tier.
• Presentation tier
• The logic in the presentation tier
should focus on user interface
concerns.
• A presentation tier devoid of business
logic will be easier to test.
• Business tier
• The business tier, which is sometimes
referred to as the application tier,
provides the implementation for the
business logic of the application,
including such things as business
rules, validations, and calculation
logic.
• Business entities for the application's
domain are placed in this tier.
• Business tier
• The business tier coordinates the
application and executes logic.
• It can perform detailed processes and
makes logical decisions.
• The business tier is the center of the
application and serves as an
intermediary between the
presentation and data tiers.
• Business tier
• It provides the presentation tier with
services, commands, and data that it
can use, and it interacts with the data
tier to retrieve and manipulate data.
• Data tier
• The data tier provides functionality to
access and manage data.
• The data tier contains a data store for
persistent storage, such as an RDBMS.
• It provides services and data for the
business tier.
• The rise of the web coincided with a
shift from two-tier (client-server)
architectures to three-tier architectures.
• With web applications and the use of
web browsers, rich client applications
containing business logic were not ideal.
Software Design and Architecture
Topic#174
END!
Software Design and Architecture
Topic#175
Module Patterns
Variations in Layered Pattern
Layered Architecture with “Sidecar”
• modules in A, B, or C can
use modules in D
• “Sidecars” often contain
common utilities such as
error handlers,
communication protocols,
or database access
mechanisms.
Segments within layers
Topic#175
END!
Software Design and Architecture
Topic#176
Component-and-Connector Patterns
Broker Pattern – I: Introduction
• Context: Many systems are constructed from a
collection of services distributed across multiple
servers.
• Implementing these systems is complex because
you need to worry about
• how the systems will interoperate
• how they will connect to each other
• how they will exchange information
• the availability of the component services.
• Problem:
• How do we structure distributed software so that
service users do not need to know the nature and
location of service providers, making it easy to
dynamically change the bindings between users
and providers?
• Solution:
• The broker pattern separates users of services (clients)
from providers of services (servers) by inserting an
intermediary, called a broker.
• When a client needs a service, it queries a broker via a
service interface.
• The broker then forwards the client’s service request to
a server, which processes the request.
• The service result is communicated from the server
back to the broker, which then returns the result (and
any exceptions) back to the requesting client.
• The first widely used implementation of the broker
pattern was in the Common Object Request Broker
Architecture (CORBA).
• Other common uses of this pattern are found in
Enterprise Java Beans (EJB) and Microsoft’s .NET platform
• Essentially any modern platform for distributed service
providers and consumers implements some form of a
broker.
• The service-oriented architecture (SOA) approach
depends crucially on brokers, most commonly in the form
of an enterprise service bus.
Software Design and Architecture
Topic#176
END!
Software Design and Architecture
Topic#177
Component-and-Connector Patterns
Broker Pattern – II: Advantages and Disadvantages
• the client remains completely ignorant of the
identity, location, and characteristics of the server.
• Because of this separation, if a server becomes
unavailable, a replacement can be dynamically
chosen by the broker.
• If a server is replaced with a different (compatible)
service, again, the broker is the only component that
needs to know of this change, and so the client is
unaffected.
• Proxies are commonly introduced as intermediaries
in addition to the broker to help with details of the
interaction with the broker, such as marshaling and
unmarshaling messages.
• The down sides of brokers are that they add
complexity (brokers and possibly proxies must be
designed and implemented, along with messaging
protocols) and add a level of indirection between a
client and a server, which will add latency to their
communication.
• Debugging brokers can be difficult because they are
involved in highly dynamic environments where the
conditions leading to a failure may be difficult to
replicate.
• The broker would be an obvious point of attack, from
a security perspective, and so it needs to be
hardened appropriately.
• Also a broker, if it is not designed carefully, can be a
single point of failure for a large and complex system.
• And brokers can potentially be bottlenecks for
communication.
Software Design and Architecture
Topic#177
END!
Software Design and Architecture
Topic#178
Component-and-Connector Patterns
MVC Pattern
Model-View-Controller (MVC)
• widely used for the UI of an application.
• It is particularly well suited to web applications,
although it can also be used for other types of
applications, such as desktop applications.
• The pattern provides a structure for building
user interfaces and provides a separation of the
different responsibilities involved.
Model-View-Controller (MVC)
• A number of popular web and application
development frameworks make use of this
pattern.
• A few examples include Ruby on Rails, ASP.NET
MVC, and Spring MVC.
•MVC is not appropriate for every situation.
• The design and implementation of three
distinct kinds of components, along with their
various forms of interaction, may be costly,
and this cost may not make sense for relatively
simple user interfaces.
•the match between the abstractions of MVC
and commercial user interface toolkits is not
perfect.
• The view and the controller split apart input
and output, but these functions are often
combined into individual widgets. This may
result in a conceptual mismatch between the
architecture and the user interface toolkit.
Software Design and Architecture
Topic#178
END!
Software Design and Architecture
Topic#179
Component-and-Connector Patterns
Pipe-and-Filter Pattern
• Context: Many systems are required to transform
streams of discrete data items, from input to
output.
• Many types of transformations occur repeatedly in
practice, and so it is desirable to create these as
independent, reusable parts.
• Problem: Such systems need to be divided into
reusable, loosely coupled components with
simple, generic interaction mechanisms.
• In this way they can be flexibly combined with
each other.
• The components, being generic and loosely
coupled, are easily reused.
• The components, being independent, can execute
in parallel.
• Solution: The pattern of interaction in the pipe-
and-filter pattern is characterized by successive
transformations of streams of data.
• Data arrives at a filter’s input port(s), is
transformed, and then is passed via its output
port(s) through a pipe to the next filter.
• A single filter can consume data from, or produce
data to, one or more ports.
Software Design and Architecture
Topic#179
END!
Software Design and Architecture
Topic#180
Component-and-Connector Patterns
Pipe-and-Filter Pattern – Strengths and Weaknesses
• typically not a good choice for an interactive
system, as it disallows cycles (which are
important for user feedback).
• having large numbers of independent filters
can add substantial amounts of
computational overhead, because each
filter runs as its own thread or process.
• may not be appropriate for long-running
computations, without the addition of some
form of checkpoint/restore functionality, as
the failure of any filter (or pipe) can cause
the entire pipeline to fail.
• Pipes buffer data during communication.
Because of this property, filters can execute
asynchronously and concurrently.
• a filter typically does not know the identity of its
upstream or downstream filters. For this reason,
pipeline pipe-and-filter systems have the
property that the overall computation can be
treated as the functional composition of the
computations of the filters, making it easier for
the architect to reason about end-to-end
behavior.
• Data transformation systems are typically
structured as pipes and filters, with each
filter responsible for one part of the overall
transformation of the input data.
• The independent processing at each step
supports reuse, parallelization, and
simplified reasoning about overall behavior.
Examples of Pipe-and-Filter Architecture
• systems built using UNIX pipes
• the request processing architecture of the Apache
web server
• Yahoo! Pipes for processing RSS feeds
• many workflow engines
• many scientific computation systems that have to
process and analyze large streams of captured data.
Software Design and Architecture
Topic#180
END!
Software Design and Architecture
Topic#181
Component-and-Connector Patterns
Client-Server Pattern
•Context: There are shared resources and
services that large numbers of distributed
clients wish to access, and for which we
wish to control access or quality of
service.
• Problem:
• By managing a set of shared resources and
services, we can promote modifiability and
reuse, by factoring out common services and
having to modify these in a single location, or a
small number of locations.
• We want to improve scalability and availability
by centralizing the control of these resources
and services, while distributing the resources
themselves across multiple physical servers.
• Solution:
• Clients interact by requesting services of
servers, which provide a set of services. Some
components may act as both clients and
servers.
• There may be one central server or multiple
distributed ones.
•Components
• clients and servers
•Connectors
• a data connector driven by a
request/reply protocol used for invoking
services.
Disadvantages
Topic#181
END!
Software Design and Architecture
Topic#182
Component-and-Connector Patterns
Shared-Data Pattern
•Context:
• Various computational components need to
share and manipulate large amounts of data.
• This data does not belong solely to any one of
those components.
•Problem:
• How can systems store and manipulate
persistent data that is accessed by multiple
independent components?
•Solution:
• Interaction is dominated by the exchange
of persistent data between multiple data
accessors and at least one shared-data
store.
• Exchange may be initiated by the
accessors or the data store.
• The connector type is data reading and
writing.
Software Design and Architecture
Topic#182
END!
Software Design and Architecture
Topic#183
Component-and-Connector Patterns
Shared-Data Pattern – Strengths and Weaknesses
Strengths
• The shared-data pattern is useful whenever
various data items are persistent and have
multiple accessors.
• Use of this pattern has the effect of decoupling
the producer of the data from the consumers
of the data; hence, this pattern supports
modifiability, as the producers do not have
direct knowledge of the consumers.
Strengths
• Consolidating the data in one or more
locations and accessing it in a common fashion
facilitates performance tuning.
• Analyses associated with this pattern usually center
on qualities such as
• data consistency,
• performance,
• security,
• privacy,
• availability,
• scalability, and
• compatibility with, for example, existing
repositories and their data.
Weaknesses
Topic#183
END!
Software Design and Architecture
Topic#184
Allocation Patterns - Multi-tier Pattern
Multi-tier Pattern
Topic#184
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 185 – 186
Monolithic Architecture
Software Design and Architecture
Topic#185
Monolithic Architecture
•A monolithic architecture is one in
which a software application is designed
to work as a single, self-contained unit.
•Applications that have this type of
architecture are common.
•The components within a monolithic
architecture are interconnected and
interdependent, resulting in tightly
coupled code.
• The different concerns of an application, such as user
interface, business logic, authorization, logging, and
database access, are not kept separate in a
monolithic architecture.
• These different pieces of functionality are intertwined
in a monolithic application.
Software Design and Architecture
Topic#185
END!
Software Design and Architecture
Topic#186
Monolithic Architecture – Strengths and Weaknesses
Benefits
•Applications with a monolithic
architecture typically have better
performance.
•Small applications that have this type of
architecture are easier to deploy
because of the simplicity of the high-
level architecture.
•In spite of the tightly coupled logic,
monolithic applications can be easier to
test and debug because they are
simpler, with fewer separate
components to consider.
• Monolithic applications are typically easy to
scale because all it takes is to run multiple
instances of the same application.
• However, different application components
have different scaling needs and we cannot
scale the components independently with a
monolithic architecture.
• We are limited to adding more instances of
the entire application in order to scale.
Drawbacks
• Monolithic applications greatly inhibit the
agility of the organization as it becomes
difficult to make changes to the software.
• continuous deployment is difficult to
achieve.
• Even if a change is made to only one
component of a monolithic application, the
entire software system will need to be
deployed.
• Organizations are required to devote more
resources, such as time and testers, to
deploy a new version of a monolithic
application.
• Low maintainability
• Tightly coupled components make it more
difficult to make changes because a change in
one part of the application is more likely to
affect other parts of the application.
• Difficult to understand
• It also takes longer for such applications to
start up, lowering the productivity of the
team during development.
•Monolithic applications require a
commitment to a particular
programming language and technology
stack.
• If a migration to a different technology is
needed, it requires the organization to commit
to rewriting the entire application.
Software Design and Architecture
Topic#186
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 187 – 212
Web Application Archetype
Software Design and Architecture
Topic#187
Web Application Architecture Overview
•Why Web Application
• Almost 23 million software developers
(2018)
Topic#187
END!
Software Design and Architecture
Topic#188
Web Application Design Considerations
Part I - Maintainability
•Partition your application logically
• Use layering to partition your application
logically into presentation, business, and data
access layers.
• helps to create maintainable code
• allows to monitor and optimize the
performance of each layer separately.
• offers more choices for scaling your
application.
•Use abstraction to implement loose
coupling between layers.
• This can be accomplished by defining
interface components, such as a façade
(or interface types/abstract base classes)
with well-known inputs and outputs that
translates requests into a format
understood by components within the
layer.
•Understand how components will
communicate with each other
• This requires an understanding of the
deployment scenarios your application must
support.
• You must determine if communication across
physical boundaries or process boundaries
should be supported, or if all components
will run within the same process.
Software Design and Architecture
Topic#188
END!
Software Design and Architecture
Topic#189
Web Application Design Considerations
Part II - Performance
•Reduce round trips.
• When designing a Web application,
consider using techniques such as caching
and output buffering to reduce round
trips between the browser and the Web
server, and between the Web server and
downstream servers.
•Consider using caching
• A well-designed caching strategy is
probably the single most important
performance-related design
consideration.
•Avoid blocking during long-running
tasks
• If you have long-running or blocking
operations, consider using an
asynchronous approach to allow the Web
server to process other incoming
requests.
Software Design and Architecture
Topic#189
END!
Software Design and Architecture
Topic#190
Web Application Design Considerations
Part III - Security
•Consider using logging and
instrumentation
• You should audit and log activities across
the layers and tiers of your application.
• These logs can be used to detect
suspicious activity, which frequently
provides early indications of an attack on
the system.
•Consider authenticating users across
trust boundaries
• You should design your application to
authenticate users whenever they cross a
trust boundary; for example, when
accessing a remote business layer from
your presentation layer.
•Do not pass sensitive data in plain text
across the network.
• Whenever you need to pass sensitive data
such as a password or authentication
cookie across the network, consider
encrypting and signing the data or using
Secure Sockets Layer (SSL) encryption.
• Design your Web application to run using a
least-privileged account
• If an attacker manages to take control of a
process, the process identity should have
restricted access to the file system and other
system resources in order to limit the possible
damage.
Software Design and Architecture
Topic#190
END!
Software Design and Architecture
Topic#191
Web Application Frame - Introduction
Web Application Frame
Topic#191
END!
Software Design and Architecture
Topic#192
Web Application Frame - Authentication
• Designing an effective authentication
strategy is important for the security and
reliability of your application.
• Improper or weak authorization can leave your
application vulnerable to spoofing attacks,
dictionary attacks, session hijacking, and other
types of attack.
Common Mistakes
Topic#192
END!
Software Design and Architecture
Topic#193
Web Application Frame - Authorization
• Authorization determines the tasks that an
authenticated identity can perform, and identifies
the resources that can be accessed. Designing an
effective authorization strategy is important for the
security and reliability of your application.
• Improper or weak authorization leads to information
disclosure, data tampering, and elevation of
privileges.
• Defense in depth is the key security principle to
apply to your application’s authorization strategy.
Common Mistakes
Topic#193
END!
Software Design and Architecture
Topic#194
Web Application Frame - Caching
• Caching improves the performance and responsiveness of
your application.
• However, incorrect caching choices and poor caching design
can degrade performance, security and responsiveness.
• You should use caching to optimize reference data lookups,
avoid network round trips, and avoid unnecessary and
duplicate processing.
• To implement caching, you must first decide when to load
data into the cache.
• Try to load cache data asynchronously or by using a batch
process to avoid client delays.
Common Mistakes
Topic#194
END!
Software Design and Architecture
Topic#195
Web Application Frame – Exception Management
• Designing an effective exception
management strategy is important for the
security and reliability of your application.
• Correct exception handling in your Web
pages prevents sensitive exception details
from being revealed to the user, improves
application robustness, and helps to avoid
leaving your application in an inconsistent
state in the event of an error.
Guidelines
• Do not use exceptions to control the logical
flow of your application.
• Do not catch exceptions unless you must
handle them, you need to strip sensitive
information, or you need to add additional
information to the exception.
• Design a global error handler to catch
unhandled exceptions.
Guidelines
• Display user-friendly messages to end users
whenever an error or exception occurs.
• Log exception related information in an error
file
• Do not reveal sensitive information, such as
passwords, through exception details.
Software Design and Architecture
Topic#195
END!
Software Design and Architecture
Topic#196
Web Application Frame – Logging and Instrumentation
• Designing an effective logging and instrumentation strategy is
important for the security and reliability of your application.
• You should audit and log activity across the tiers of your
application.
• These logs can be used to detect suspicious activity, which
frequently provides early indications of an attack on the
system, and help to address the repudiation threat where users
deny their actions.
• Log files may be required in legal proceedings to prove the
wrongdoing of individuals.
• Generally, auditing is considered most authoritative if the
audits are generated at the precise time of resource access and
by the same routines that access the resource.
Guidelines
• Consider auditing for user management events.
• Consider auditing for unusual activities.
• Consider auditing for business-critical operations.
• Create secure log file management policies, such as
restricting the access to log files, allowing only write
access to users, etc.
• Do not store sensitive information in the log or audit
files.
Software Design and Architecture
Topic#196
END!
Software Design and Architecture
Topic#197
Web Application Frame – Navigation
• Design your navigation strategy in a way
that separates it from the processing logic.
• Your strategy should allow users to navigate
easily through your screens or pages.
• Designing a consistent navigation structure
for your application will help to minimize
user confusion as well as reduce the
apparent complexity of the application.
Guidelines
Topic#197
END!
Software Design and Architecture
Topic#198
Web Application Frame – Page Layout
• Design your application so that the page layout
can be separated from the specific UI
components and UI processing.
• When choosing a layout strategy, consider
whether designers or developers will be
building the layout.
• If designers will be building the layout, choose a
layout approach that does not require coding or
the use of development-focused tools.
Guidelines
• Use Cascading Style Sheets (CSS) for layout
whenever possible.
• Use table-based layout when you need to
support a grid layout, but remember that
table-based layout can be slow to render,
does not have full cross-browser support,
and there may be issues with complex
layout.
Guidelines
Topic#198
END!
Software Design and Architecture
Topic#199
Web Application Frame – Page Rendering
• When designing for page rendering, you
must ensure that you render the pages
efficiently and maximize interface usability.
Guidelines
• Consider data-binding options.
• For example, you can bind custom objects or datasets to
controls.
• Consider using Asynchronous JavaScript and XML
(AJAX) for an improved user experience and better
responsiveness.
• Consider using data-paging techniques for large
amounts of data to minimize scalability issues.
Guidelines
• Consider designing to support localization in UI
components.
• Abstract the user process components from
data rendering and acquisition functions.
Software Design and Architecture
Topic#199
END!
Software Design and Architecture
Topic#200
Web Application Frame – Presentation Entity
• Presentation entities store the data that you will use
to manage the views in your presentation layer.
• Presentation entities are not always necessary.
• Consider using presentation entities only if the
datasets are sufficiently large or complex that they
must be stored separately from the UI controls.
• Design or choose appropriate presentation entities
that you can easily bind to UI controls.
Guidelines
Topic#200
END!
Software Design and Architecture
Topic#201
Web Application Frame – Request Processing
•When designing a request-processing
strategy, you should ensure separation
of concerns by implementing the
request-processing logic separately from
the UI.
Guidelines
• Consider centralizing the common pre-processing
and post-processing steps of Web page requests
to promote logic reuse across pages.
• Consider dividing UI processing into three distinct
roles—model, view, and controller/presenter—
by using the Model-View-Controller (MVC) or
Model-View-Presenter (MVP) pattern.
Guidelines
• If you are designing views for handling large
amounts of data, consider giving access to the
model from the view by using the Supervising
Controller pattern, which is a form of the MVP
pattern.
Software Design and Architecture
Topic#201
END!
Software Design and Architecture
Topic#202
Web Application Frame – Session Management
• When designing a Web application, an
efficient and secure session-management
strategy is important for performance,
security and reliability.
• You must consider session-management
factors such as what to store, where to store
it, and how long information will be kept.
Guidelines
• If you have a single Web server, require optimum
session state performance, and have a relatively
limited number of concurrent sessions, use the
in-process state store.
• If you have a single Web server, your sessions are
expensive to rebuild, and you require durability
in the event of a restart, use the session state
service running on the local Web server.
Guidelines
• If you are storing state on a separate server,
protect your session state communication
channel.
• For security reasons, use session expiry (timeout)
• Prefer basic types for session data to reduce
serialization costs.
Software Design and Architecture
Topic#202
END!
Software Design and Architecture
Topic#203
Web Application Frame – Validation
• Designing an effective validation solution is
important for the security and reliability of
your application.
• Improper or weak authorization can leave
your application vulnerable to cross-site
scripting attacks, SQL injection attacks,
buffer overflows, and other types of input
attack.
Guidelines
Topic#203
END!
Software Design and Architecture
Topic#204
Web Application Frame
Presentation Layer Considerations
• The presentation layer of your Web
application displays the UI and facilitates
user interaction.
• The design should focus on separation of
concerns, where the user interaction logic is
decoupled from the UI components.
Guidelines
Topic#204
END!
Software Design and Architecture
Topic#205
Web Application Frame
Business Layer Considerations
• When designing the business layer for your
Web application, consider how to
implement the business logic and long-
running workflows.
• Design business entities that represent the
real world data, and use these to pass data
between components.
Guidelines
Topic#205
END!
Software Design and Architecture
Topic#206
Web Application Frame
Data Layer Considerations
• Design a data layer for your Web application
to abstract the logic necessary to access the
database.
• Using a separate data layer makes the
application easier to configure and maintain.
• The data layer may also need to access
external services using service agents.
Guidelines
Topic#206
END!
Software Design and Architecture
Topic#207
Web Application Frame
Service Layer Considerations
• Consider designing a separate service layer
if you plan to deploy your business layer on
a remote tier, or if you plan to expose your
business logic using a Web service.
Guidelines
• If your business layer is on a remote tier, design
coarse-grained service methods to minimize the
number of client-server interactions, and to provide
loose coupling.
• Design the services without assuming a specific client
type.
• Design the services to be idempotent, assuming that
the same message request may arrive multiple times.
Software Design and Architecture
Topic#207
END!
Software Design and Architecture
Topic#208
Web Application Frame
Testing and Testability Considerations
• Testability is a measure of how well your system or
components allow you to create test criteria and
execute tests to determine if the criteria are met.
• You should consider testability when designing your
architecture because it makes it easier to diagnose
problems earlier and reduce maintenance cost.
• To improve the testability of your application, you
can use logging events, provide monitoring
resources, and implement test interfaces.
Guidelines
Topic#208
END!
Software Design and Architecture
Topic#209
Web Application Frame
Performance Considerations
• You should identify your performance
objectives early in the design phase of a Web
application by gathering the non-functional
requirements.
• Response time, throughput, CPU, memory,
and disk I/O are a few of the key factors you
should consider when designing your
application.
Guidelines
Topic#209
END!
Software Design and Architecture
Topic#210
Web Application Frame
Security Considerations
• Security is an important consideration for
protecting the integrity and privacy of the data
and the resources of your Web application.
• You should design a security strategy for your
Web application that uses tested and proven
security solutions, and implement
authentication, authorization, and data
validation to protect your application from a
range of threats.
Guidelines
Topic#210
END!
Software Design and Architecture
Topic#211
Web Application Frame
Deployment Considerations
• When deploying a Web application, you should
take into account how layer and component
location will affect the performance, scalability,
and security of the application.
• You might also need to consider design trade-offs.
• Use either a distributed or a non-distributed
deployment approach, depending on the business
requirements and infrastructure constraints.
Guidelines
Topic#211
END!
Software Design and Architecture
Topic#212
Web Application Frame
Load Balancing
• When you deploy your
Web application on
multiple servers, you
can use load balancing
to distribute requests so
that they are handled by
different Web servers.
• This helps to maximize
response times,
resource utilization, and
throughput.
Guidelines
Topic#212
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 213-217
Architecture in the cloud
Software Design and Architecture
Topic#213
Cloud Computing – Introduction
Cloud Computing
Topic#214
Cloud Computing – Basic Definitions
Basic Cloud Definitions
•On-demand self-service.
• A resource consumer can unilaterally
provision computing services, such as server
time and network storage, as needed
automatically without requiring human
interaction with each service’s provider.
Basic Cloud Definitions
•On-demand self-service.
• This is sometimes called empowerment of
end users of computing resources.
• Examples of resources include storage,
processing, memory, network bandwidth,
and virtual machines.
•Ubiquitous network access.
•Cloud services and resources are
available over the network and
accessed through standard networking
mechanisms that promote use by a
heterogeneous collection of clients.
•This capability is independent of
location and device;
• all you need is a client and the Internet.
•Resource pooling
•The cloud provider’s computing
resources are pooled.
•In this way they can efficiently serve
multiple consumers.
•The provider can dynamically assign
physical and virtual resources to
consumers, according to their
instantaneous demands.
•Location independence.
•The location independence provided
by ubiquitous network access is
generally a good thing.
•Rapid elasticity.
•Due to resource pooling, it is easy for
capabilities to be rapidly and elastically
provisioned, in some cases
automatically, to quickly scale out or in.
•To the consumer, the capabilities
available for provisioning often appear
to be virtually unlimited.
•Multi-tenancy.
•Multi-tenancy is the use of a single
application that is responsible for
supporting distinct classes or users.
•Each class or user has its own set of
data and access rights, and different
users or classes of users are kept
distinct by the application.
Software Design and Architecture
Topic#214
END!
Software Design and Architecture
Topic#215
Cloud Computing – Service Models and Deployment
Options
Software as a Service (SaaS)
•Private cloud.
• The cloud infrastructure is owned solely
by a single organization and operated
solely for applications owned by that
organization.
• The primary purpose of the organization is
not the selling of cloud services.
Deployment Models
•Public cloud.
• The cloud infrastructure is made available
to the general public or a large industry
group and is owned by an organization
selling cloud services.
Software Design and Architecture
Topic#215
END!
Software Design and Architecture
Topic#216
Cloud Computing – Multitenancy
•Multi-tenancy applications are
architected explicitly to have a single
application that supports distinct sets of
users.
•The economic benefit of multi-tenancy
is based on the reduction in costs for
application update and management.
• Consider what is involved in updating an
application for which each user has an
individual copy on their own desktop.
• New versions must be tested by the IT
department and then pushed to the
individual desktops.
•Different users may be updated at
different times because of disconnected
operation, user resistance to updates, or
scheduling difficulties.
•Incidents result because the new version
may have some incompatibilities with
older versions, the new version may
have a different user interface, or users
with old versions are unable to share
information with users of the new
version.
•With a multi-tenant application, all of
these problems are pushed from IT to
the vendor, and some of them even
disappear.
•Any update is available at the same
instant to all of the users, so there are
no problems with sharing.
•Any user interface changes are referred
to the vendor’s hotline rather than the
IT hotline, and the vendor is responsible
for avoiding incompatibilities for older
versions.
•The problems of upgrading do not
disappear, but they are amortized over all of
the users of the application rather than
being absorbed by the IT department of
every organization that uses the application.
•This amortization over more users results in
a net reduction in the costs associated with
installing an upgraded version of an
application.
Software Design and Architecture
Topic#216
END!
Software Design and Architecture
Topic#217
Cloud Computing – Architecting in Cloud Environment
•In some ways, the cloud is a platform,
and architecting a system to execute in
the cloud, especially using IaaS, is no
different than architecting for any other
distributed platform.
•That is, the architect needs to pay
attention to usability, modifiability,
interoperability, and testability, just as
he or she would for any other platform.
•The quality attributes that have some
significant differences are security,
performance, and availability.
Security
•Options:
•Stateless services - mirroring
•Data stored across zones - partition
•Graceful degradation
Software Design and Architecture
Topic#217
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 218-221
Service-Oriented Architecture
Software Design and Architecture
Topic#218
Service-Oriented Architecture – Introduction
• Service-oriented architecture (SOA) is an
architectural pattern for developing
software systems by creating loosely
coupled, interoperable services that work
together to automate business processes.
• A service is a part of a software application
that performs a specific task, providing
functionality to other parts of the same
software application or to other software
applications.
• Some examples of service consumers
include web applications, mobile
applications, desktop applications, and
other services.
•SOA achieves a SoC, which is a design
principle that separates a software system
into parts, with each part addressing a
distinct concern.
•A key aspect of SOA is that it decomposes
application logic into smaller units that
can be reused and distributed.
•By decomposing a large problem into
smaller, more manageable concerns
satisfied by services, complexity is
reduced and the quality of the software is
improved.
•Each service in a SOA encapsulates a certain
piece of logic.
•This logic may be responsible for a very
specific task, a business process, or a sub-
process.
•Services can vary in size and one service can
be composed of multiple other services to
accomplish its task.
Software Design and Architecture
Topic#218
END!
Software Design and Architecture
Topic#219
What Makes Service-Oriented Architecture Different from
other Distributed Solutions?
•SOA shares similarities with earlier
distributed solutions
•Distributing application logic and
separating it into smaller, more
manageable units is not what makes
SOA different from previous approaches
to distributed computing.
•Naturally, you might think the biggest
difference is the use of web services, but
keep in mind that SOA does not require
web services, although they happen to
be a perfect technology to implement
with SOA.
•What really sets SOA apart from a
traditional distributed architecture is not
the use of web services, but how its core
components are designed.
•SOA achieves a SoC, which is a design
principle that separates a software
system into parts, with each part
addressing a distinct concern.
•Services can vary in size and one service
can be composed of multiple other
services to accomplish its task.
Software Design and Architecture
Topic#219
END!
Software Design and Architecture
Topic#220
Benefits of Service-Oriented Architecture
• Increases alignment between business and
technology
• Business logic, in the form of business entities
and business processes, exists in the form of
physical services with an SOA.
• Promotes federation within an organization
• Organizations have the flexibility to choose
whether they want to replace certain systems,
allowing them to use a phased approach to
migration.
• Allows for vendor diversity
• Increases intrinsic interoperability
• It allows for the sharing of data and the reuse of
logic. Different services can be assembled
together to help automate a variety of business
processes.
• Works well with agile development
methodologies
• each task can be made to be manageable in size
and more easily understood.
Software Design and Architecture
Topic#220
END!
Software Design and Architecture
Topic#221
Challenges with Service-Oriented Architecture
•SOA solutions may allow organizations
to do more, including automating more
of their business processes.
•This can cause enterprise architectures
to grow larger in scope and functionality
as compared to legacy systems.
•Taking on a larger scope of functionality
will add complexity to a software
system.
•In an SOA, new layers may be added to
software architectures, providing more
areas where failure can occur and
making it more difficult to pinpoint
those failures.
•In addition, as increasing numbers of
services are created, deploying new
services and new versions of existing
services must be managed carefully so
that troubleshooting can be effective
when an error occurs with a specific
transaction.
Software Design and Architecture
Topic#221
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 222-226
Microservice Architecture
Software Design and Architecture
Topic#222
Microservice Architecture - Introduction
•Microservice architecture emerged
as the result of the shortcomings
and drawbacks of the traditional
service-oriented architecture (SOA)
and monolithic architecture.
•The microservice architecture (MSA)
pattern builds software applications
using small, autonomous, independently
versioned, self-contained services.
•These services use well-defined
interfaces and communicate with each
other over standard, lightweight
protocols.
•Interaction with a microservice takes
place through a well-defined interface.
Topic#222
END!
Software Design and Architecture
Topic#223
Characteristics of microservice architecture
•Small, focused services
•Well-defined service interfaces
•Autonomous and independently deployable
services
•Independent data storage
•Communicating with lightweight protocols
•Better fault isolation
Microservice Architecture Example
•Incoming requests are commonly
handled by an API gateway, which
serves as the entry point to the
system.
•It is an HTTP server that takes requests
from clients and routes them to the
appropriate microservice through its
routing configuration.
Software Design and Architecture
Topic#223
END!
Software Design and Architecture
Topic#224
Designing Polyglot Services
•Monolithic applications focus on using
a particular programming language
and technology stack.
•Because that type of application is
written as a single unit, it is more
difficult to take advantage of different
types of technology.
•Complex applications need to solve a
variety of problems.
•Being able to select different
technologies for different problems
can be useful rather than trying to
solve all of the problems with a single
technology.
•Polyglot
•a person who knows and is able to use
several languages
•One of the many advantages of
using a microservice architecture is
that it affords you the option of
using multiple programming
languages, runtimes, frameworks,
and data storage technologies.
•Having polyglot microservices is certainly not
required when using a microservice
architecture.
•In many cases, an organization will focus on a
limited number of technologies, and the
skillsets of the development team will reflect
that.
•However, software architects should be
aware of the option and recognize
opportunities where it can be used
effectively.
•Two of the concepts related to polyglot
microservices are:
•polyglot programming
• With polyglot programming, a single
application uses multiple programming
languages in its implementation.
•polyglot persistence
• multiple persistence options are used within
a single application
Software Design and Architecture
Topic#224
END!
Software Design and Architecture
Topic#225
Stateless versus Stateful Microservices
•Stateful applications store state from
client requests on the server itself
and use that state to process further
requests.
• When a user sends a login request, it
enables login to be true and user
authenticated now, and on the second
request, the user sees the dashboard.
•Stateful applications don’t need to
make a call to DB second time as
session info stored on the server
itself, hence it is faster.
Problems with Stateful Apps
Topic#225
END!
Software Design and Architecture
Topic#226
Microservice Architecture Challenges
•a microservice architecture introduces
complexity simply not found in a
monolithic application.
•When multiple services are working
together in a distributed system and
something goes wrong, there is added
complexity in figuring out what and
where something failed.
•Decomposing a complex system into
the right set of microservices can be
difficult.
•It requires a knowledge of the domain
and can be somewhat of an art.
•You don't want a system with services
that are too fine-grained, resulting in a
large number of services.
•As the number of services increase, the
management of those services becomes
increasingly complex.
•Balancing between fine-grained and
coarse-grained services
•Controlling coupling between services that
are deployed together
• If you are not careful, you will end up with a
microservice architecture that is a monolith in
disguise.
•The use of multiple databases is another
challenge when using a microservice
architecture.
•It is common for a business transaction to
update multiple entities, which will require
the use of multiple microservices.
•With each one having its own database, this
means that updates must take place in
multiple databases.
Software Design and Architecture
Topic#226
END!
Software Design and Architecture
Fakhar Lodhi
Topics Covered: 227
Summing it up - What every software architect
should know
•Business Drives
•Understand the Business
Domain
•Architecting Is About Balancing
•Architectural Tradeoffs
•Simplify Essential Complexity;
Diminish Accidental Complexity
•Simplicity Before Generality, Use
Before Reuse
•Architects’ Focus Is on the
Boundaries and Interfaces
•Communication Is King
•Record Your Rationale
•Share Your Knowledge and
Experiences
•Quantify.
•Application Architecture
Determines Application
Performance
•It’s Never Too Early to Think About
Performance
•Everything Will Ultimately Fail
•Time Changes Everything
•Architects Must Be Hands On
•Try Before Choosing
•There Is No One-Size-Fits-All
Solution
•Software Architecture Has Ethical
Consequences
Software Design and Architecture
Topic#227
END!