Software entities like classes, modules and functions should be open for extension but closed for modifications.
BAD Example:
AreaCalculator need to be
modified for every new shape.
Shape:
public interface Shape {
}
Square:
public class Square implements Shape{
private double side = 0;
public Square(double side){
this.side = side;
}
public double getSide(){
return side;
}
}
Circle:
public class Circle implements Shape{
private double radius = 0;
public Circle(double radius){
this.radius = radius;
}
public double getRadius(){
return radius;
}
}
AreaCalculator:
public class AreaCalculator {
public double area(Shape[]
shapes){
double area = 0;
double value = 0;
for(Shape shape :
shapes){
if(shape instanceof Square){
value
= ((Square)shape).getSide();
area
+= value * value;
}else if(shape instanceof Circle){
value
= ((Circle) shape).getRadius();
area
+= Math.PI * value * value;
}
}
return area;
}
}
Good Example:
In following
code, we can add new shapes (Shape – Open for extensions) and those are not going to impact AreaCalculator (Closed for Modifications).
Shape:
public interface Shape {
public double area();
}
Square:
public class Square implements Shape {
private double side = 0;
public Square(double side){
this.side = side;
}
public double area(){
return (side * side);
}
}
Circle:
public class Circle implements Shape{
private double radius = 0;
public Circle(double radius){
this.radius = radius;
}
public double area() {
return (Math.PI * radius * radius);
}
}
AreaCalculator:
public class AreaCalculator
{
public double area(Shape[]
shapes){
double area = 0;
for(Shape shape :
shapes){
area += shape.area();
}
return area;
}
}
No comments:
Post a Comment