Professional Documents
Culture Documents
S.O.L.I.D: Software
Engineering Principles
Eduardo Figueiredo
http://www.dcc.ufmg.br/~figueiredo
S.O.L.I.D Principles
S Single-responsibility principle
O Open-closed principle
L Liskov substitution principle
I Interface segregation principle
D Dependency inversion principle
Single-Responsibility Principle
Single Responsibility Principle
Rectangle
Geometry Graphical
Application Application
+ draw()
+ area()
GUI
Example of Violation
The Rectangle class has two responsibilities
Rectangle
Geometry Graphical
Application Application
+ draw()
+ area()
Application 1 never
draws the rectangle GUI
on screen
Application 2 draws the
rectangle on screen
Separated Responsibilities
Geometry Graphical
Application Application
+ area() + draw()
Open-Closed Principle
Open-Closed Principle
# length # radius
+ getLength() + getRadius()
Geometry
Application
Open for Extension
Shape
Geometry
Solution: client Application
is coupled only + area()
to abstraction
Square Circle
public double sumArea(Shape[] shapes) {
double area = 0;
# length # radius
for (int i = 0; i<shapes.length; i++) {
area += shapes[i].area(); + getLength() + getRadius()
} + area() + area()
return area;
}
Liskov Substitution Principle
Liskov Substitution Principle
# height
A square does not need
# width both height and width fields
+ setHeight()
+ getHeight()
(and other members)
...
It inherits them anyway
The methods setHeight() and
Square
setWidth() are inappropriate
How to fix them?
Example of Violation
Rectangle Workaround: override
# height
the setHeight() and
# width setWidth() methods
+ setHeight()
+ getHeight() public class Square extends Rectangle {
... public void setHeight(int h) {
this.height = h;
this.width = h;
}
IShape
Both square and cube
are shapes
+ area() The “is a” relationship holds
+ volume()
Square Cube
+ area() + area()
+ volume()
Dependency Inversion
Principle
Dependency Inversion Principle
PasswordReminder DBConnection
+ restoreTip() + connect()
...
MySQLConnection
+ connect()
...
Template Method Example