Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 57 ยท Design Principles

Open/Closed Principle

Learn the Open/Closed Principle: extend behavior without editing tested code. Replace if-else chains with polymorphism and strategy in a runnable discount example.

The Open/Closed Principle (OCP) says that software entities (classes, modules, functions) should be open for extension but closed for modification. In plain words: when a new requirement arrives, you should be able to add new code rather than edit code that already works and is already tested.

The phrase sounds contradictory until you see the trick. The code is closed because its source does not change. It is open because its behavior can still grow, through a point of variation built in advance: an interface, a function parameter, a list of plugins. Done well, adding the tenth discount type feels just like adding the second.

Open and closed at once

Open New behavior can be added.
Closed Working code is not edited.
Extension point An interface the new code plugs into.
1 / 2

The if-else chain problem

A shop applies discounts by customer category. A first version might look like this.

JS Before: every new rule edits the function

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This is fine for four types. The trouble starts when the marketing team asks for "buy one get one", "free shipping over 100", "seasonal sale" and "loyalty points". Each request edits finalPrice, risks the other branches, and forces everything to be retested. The function is open to modification and closed to extension: exactly the wrong way around.

Making the variation explicit

The fix is to turn each rule into its own object (or function) with the same shape, and have the pricing code loop over them. This is the Strategy pattern in action, and it is the standard way to achieve OCP.

JS After: add a rule by adding an object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

finalPrice was never edited, yet the behavior changed. Notice one new complication: the rules now run in order, and order matters (a coupon applied before a percentage discount gives a different price). Extension points often bring such questions, and you must answer them deliberately, perhaps with a priority field.

The same idea with classes

In class-based languages the extension point is an interface. Each rule is a class implementing it. This Java version is read-only; it shows the same structure.

Java
interface DiscountRule {
    boolean appliesTo(Customer customer);
    double apply(double price);
}

class VipDiscount implements DiscountRule {
    public boolean appliesTo(Customer c) { return c.type() == CustomerType.VIP; }
    public double apply(double price) { return price * 0.9; }
}

class PricingService {
    private final List<DiscountRule> rules;
    PricingService(List<DiscountRule> rules) { this.rules = rules; }

    double finalPrice(double subtotal, Customer customer) {
        double price = subtotal;
        for (DiscountRule rule : rules) {
            if (rule.appliesTo(customer)) price = rule.apply(price);
        }
        return price;
    }
}

In C++ the same extension point is a base class with pure virtual functions and a std::vector<std::unique_ptr<DiscountRule>>. In Python or JavaScript it can simply be a list of functions, as in the runnable example. The mechanism changes; the principle does not.

Polymorphism as the engine

OCP relies on polymorphism: the caller treats all rules the same, and each rule behaves differently. Without it, the only way to vary behavior is to branch on a type, which scatters the same if or switch throughout the code. A useful rule of thumb: repeated switches on the same type are a polymorphism waiting to happen.

Closed against what? Choose your extension points

No code can be closed against every change. If you try to make everything extensible, you build a framework nobody asked for. The sensible approach:

  1. Write the simplest code first. For the first discount type, a plain function is fine.
  2. When the first change arrives, you learn what kind of change to expect. The second discount type tells you that discount rules are a point of variation.
  3. Add the extension point at that moment, a technique sometimes called "fool me once". You are closed against that kind of change from then on.
  4. Avoid speculative interfaces for variation that may never come.

OCP is also not an excuse to forbid edits. Fixing a bug in finalPrice is a legitimate modification. The principle is about feature additions not requiring edits to stable logic.

Another kind of extension: registries

A common way to get OCP is a registry: a map from a name to a handler. New handlers register themselves, and the dispatcher stays unchanged. This is how plugin systems, command-line tools and web frameworks route requests.

JS A handler registry

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does 'open for extension, closed for modification' mean in practice?

    OCP does not forbid bug fixes. It asks that adding a feature does not require changing stable logic, typically through an extension point.
  2. 2. Which code smell most often signals a missing OCP extension point?

    An ever-growing chain of branches on a type means each feature edits the same function, so behavior is not extensible.
  3. 3. Which pattern is the most direct way to achieve OCP for interchangeable rules like discounts?

    Strategy puts each rule behind a common interface so rules can be added without changing the code that uses them.
  4. 4. After adding the extension point and many rules, a new problem appears: results differ depending on rule order. What does this show?

    Making code extensible does not make interactions between extensions disappear. Priorities or explicit ordering are often needed.

Summary

  • OCP: extend behavior by adding code, not by editing stable, tested code.
  • The mechanism is an extension point: an interface, a function parameter, or a registry of handlers.
  • Long conditional chains on a type are the classic smell; polymorphism or strategy objects replace them.
  • Add extension points when real variation appears, since being closed against everything is impossible and costly.
  • Extensions can interact (ordering, conflicts), so design that part deliberately.

Next, the principle that keeps those extensions honest: Liskov Substitution Principle.