Open/Closed: add a shape without editing the calculator
Circle and Rectangle each know their own area. AreaCalculator never needs an if/else for shape types.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Open/Closed means we can add new behavior without editing code that already works. AreaCalculator is closed: it never changes, no matter how many shapes exist. It is open to extension: a new shape just inherits Shape and provides its own Area().
Code
var shapes = new List<Shape> {
new Circle { Radius = 3 }, new Rectangle { Width = 4, Height = 5 } };
Console.WriteLine(new AreaCalculator().Total(shapes));
abstract class Shape {
public abstract double Area();
}
class Circle : Shape {
public double Radius;
public override double Area() => Math.PI * Radius * Radius;
}
class Rectangle : Shape {
public double Width, Height;
public override double Area() => Width * Height;
}
class AreaCalculator {
public double Total(List<Shape> shapes) =>
shapes.Sum(s => s.Area());
}abstract class Shape {
abstract double area();
}
class Circle extends Shape {
double radius;
Circle(double radius) { this.radius = radius; }
@Override double area() { return Math.PI * radius * radius; }
}
class Rectangle extends Shape {
double width, height;
Rectangle(double width, double height) { this.width = width; this.height = height; }
@Override double area() { return width * height; }
}
class AreaCalculator {
double total(List<Shape> shapes) {
return shapes.stream().mapToDouble(Shape::area).sum(); }
}
public class Main {
public static void main(String[] args) {
List<Shape> shapes = List.of(
new Circle(3), new Rectangle(4, 5));
System.out.println(new AreaCalculator().total(shapes));
}
}class Shape {
public:
virtual double area() const = 0;
virtual ~Shape() = default;
};
class Circle : public Shape {
public:
double radius;
explicit Circle(double r) : radius(r) {}
double area() const override { return M_PI * radius * radius; }
};
class Rectangle : public Shape {
public:
double width, height;
Rectangle(double w, double h) : width(w), height(h) {}
double area() const override { return width * height; }
};
class AreaCalculator {
public:
double total(const vector<Shape*>& shapes) const {
double sum = 0; for (auto* s : shapes) sum += s->area();
return sum;
}
};
int main() {
Circle c{3}; Rectangle r{4, 5};
vector<Shape*> shapes{&c, &r};
cout << AreaCalculator().total(shapes) << "\n";
}from abc import ABC, abstractmethod
import math
class Shape(ABC):
@abstractmethod
def area(self) -> float: ...
class Circle(Shape):
def __init__(self, radius): self.radius = radius
def area(self) -> float: return math.pi * self.radius ** 2
class Rectangle(Shape):
def __init__(self, width, height): self.width, self.height = width, height
def area(self) -> float: return self.width * self.height
class AreaCalculator:
def total(self, shapes) -> float:
return sum(s.area() for s in shapes)
shapes = [Circle(3), Rectangle(4, 5)]
print(AreaCalculator().total(shapes))Tips
- The alternative is an AreaCalculator with "if shape is Circle ... else if shape is Rectangle ...". Every new shape would mean editing that method and risking the shapes that already work.
- This is only worth it when new variants are likely. Do not add an abstract base class for something that will only ever have one kind.
In the .NET library
Add a Triangle class tomorrow, give it its own Area(), and AreaCalculator.Total() handles it correctly without a single line of AreaCalculator being touched.