The father of this principle is Bertrand Meyer, this principle was first presented in Bertrand’s Book Object Oriented Software Construction. What this principle states is that a module or class should be open for extension, but close for modification. But how’s that possible, what do we should understand for extension and close.
Extension: It should be easy to change the behavior of that class or module.
Close: Source code should not change.
The main benefits of use this principle is:
• Help with the maintenance of code.
• Clearer code
As an example of the violation of this principle we can consider a class that is in charge of drawing different shapes, it should be clear that this violates this principle because each time we want to add a new shape we have to modify the code.
Code Violating the OCP
class ShapeEditor{
public void drawshape(Shape shape){
if (shape.type == 1)
drawtriangle(shape);
else
if (shape.type == 2)
drawcircle(shape);
}
public void drawcircle(Circle circle) {....}
public void drawtriangle(Rectangle rectangle) {....}
}
class Shape{
int type;
}
class Triangle extends Shape {
triangle() {
super. type=1;
}
}
class Circle extends Shape {
circle() {
super. type=2;
}
}
A possible solution could be:
class ShapeEditor {
public void drawShape(Shape shape) {
shape.draw();
}
}
class Shape {
abstract void draw();
}
class Triangle extends Shape {
public void draw() {
// draw the triangle
}
}
class Circle extends Shape {
public void draw() {
// draw the circle
}
}
No hay comentarios:
Publicar un comentario