Search⌘ K
AI Features

Implementing OCP in OOP

Explore how implementing the Open-Closed Principle (OCP) in Java helps you design code that accommodates new features without altering existing code. Understand how this principle works alongside DIP and LSP to create stable and flexible designs, reducing errors and simplifying maintenance while supporting seamless extensibility.

In this lesson, we’ll see how OCP (Open-Closed Principle) 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.

Keeping code open for growth, closed for tweaks

OCP results in code that’s open to extension but closed to modification. We saw this idea at work when we looked at DIP. Let’s now review the code refactoring we did in light of OCP.

Java
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) {
switch (s.getType()) {
case "textbox":
var t = (TextBox) s;
g.drawText(t.getText());
break;
case "rectangle":
var r = (Rectangle) s;
for (int row = 0;
row < r.getHeight();
row++) {
g.drawLine(0, r.getWidth());
}
}
}
}
}

Adding a new type of shape requires modification of the code inside the draw() method. We’ll be ...