Skip to content
LLD Learn/SOLID Principles
Browsing as a guest. Sign in to save your progress and earn XP as you complete chapters.

Open/Closed Principle

4 min read

You'll learn to

  • -Explain "open for extension, closed for modification" with a concrete before and after
  • -Recognize a growing if/elif chain on a type as the usual sign of a violation
  • -Know where the one remaining choice lives, and what OCP does not forbid (bug fixes)

Tip: the highlighter is on - just select any text below to mark it. Use the highlighter button up top to change color or turn it off. Highlights are saved on this device only. Log in to save them to your account instead.

The Open/Closed Principle (OCP) says a piece of code should be open for extension but closed for modification. In plain words, you should be able to add new behavior without editing code that already works and has already been tested. The usual way to do that is polymorphism: instead of one method that branches on the type of thing, give every type its own class with the same shape.

An Analogy: Apps on a Phone

When you install a new app, the phone gains a new ability, and nobody re-opens the operating system to add it. The phone is closed for modification and open for extension. A shop till that needed its software rewritten for every new discount would be the opposite.

The Growing Switch Statement Is the Tell

The most common OCP violation on a whiteboard is a method that branches on a type or a label and gets edited again for every new case. Imagine a discount calculator. It starts with students, then gets a branch for seniors, then one for the military. It works, but every new branch means re-opening, re-testing and re-risking a method that every earlier case already depends on.

From a growing switch to extension without modification
# Before: every new discount type means editing this method again
def calculate_discount(customer_type: str, price: float) -> float:
    if customer_type == "student":
        return price * 0.9
    elif customer_type == "senior":
        return price * 0.85
    elif customer_type == "military":  # <- added later, method edited again
        return price * 0.8
    return price

# After: closed for modification, open for extension
class DiscountStrategy(ABC):
    @abstractmethod
    def apply(self, price: float) -> float: ...

class StudentDiscount(DiscountStrategy):
    def apply(self, price: float) -> float: return price * 0.9

class MilitaryDiscount(DiscountStrategy):  # <- new file, zero existing code touched
    def apply(self, price: float) -> float: return price * 0.8

The demo below is the "after" version in full. Each discount is its own class with the same method. The checkout code never changes, and the 'military' discount is a brand new class that touches nothing old.

Press Run: three discounts on a 100.00 price, one checkout function that never changed

Where Does the Choice Go?

Somewhere the program must still decide that a given customer gets the student discount. OCP does not make that choice disappear. It moves it to one small place at the edge, such as a lookup table from customer type to discount object. Adding a veteran discount is then one new class and one new line in that table, instead of a new branch inside the logic that every discount shares.

OCP Is Not "Never Change Anything"

The principle does not freeze existing code forever. Bug fixes and genuine changes to existing behavior are normal. If the student discount should now be 15 percent off, you edit the student class. OCP is about adding a new variant of existing behavior, such as a new discount, a new payment method or a new notification channel. "Add a new kind of X" should mean writing a new class, not re-opening a method that every existing kind of X relies on.

OCP and the Strategy pattern, in a later chapter, are close cousins. OCP is the principle, and Strategy is very often the concrete pattern used to satisfy it when the part that varies is which rule or algorithm applies.

Interview Signal

You see a NotificationSender class with a send(type, message) method containing if type == "email" / elif type == "sms" branches. How would you flag this?

Weak Answer

"That's fine, it works and handles both cases correctly."

Strong Answer

"It works today, but every new channel means editing this method again and re-risking the existing branches - that's an Open/Closed violation. I'd define a NotificationChannel interface with an EmailChannel and SmsChannel implementation, and have the sender iterate over a list of channels instead of branching on type. A new channel becomes a new class, not a new elif."

Check Yourself1 / 5

What does "open for extension, closed for modification" mean in practice?

Discussion0

Join the Discussion

Sign in to leave comments, reply to others, or like insights.

Sign In to ScaleDojo

No comments yet. Be the first to start the thread!