OCP – extensible design
In this section, we’ll see how OCP helps us write code that we can add new features to, without changing the code itself. This does sound like an impossibility at first, but it flows naturally from DIP combined with LSP.
OCP results in code that is open to extension but closed to modification. We saw this idea at work when we looked at DIP. Let’s review the code refactoring we did in the light of OCP.
Let’s start with the original code for the Shapes
class, as follows:
public class Shapes { private final List<Shape> allShapes = new ArrayList<>(); public void add(Shape s) { allShapes.add(s); } public void draw(Graphics g) { for (Shape s : allShapes) { ...