Skip to content
DiaGO

Open-Closed Principle

Software should be open for extension but closed for modification - add behavior with new code, not by editing working code.

Bertrand Meyer coined the Open-Closed Principle in 1988: software entities should be open for extension but closed for modification. The modern, polymorphism-based reading is more practical: when a new requirement arrives, you should be able to satisfy it by writing new code, not by editing code that already works, has passed review, and is covered by tests.

The reasoning is about risk, not elegance. Every edit to a working module can introduce a regression, forces re-testing, and invites merge conflicts in code that other teams depend on. A module you never have to reopen is a module you can never break. OCP does not promise that requirements stop changing — it says you can position the impact of a change so it lands in fresh code instead of proven code.

The mechanism: abstraction plus polymorphism

OCP is not a vague aspiration; it has exactly one implementation technique. You introduce an abstraction point — an interface or abstract class that fixes a contract — and let callers depend on that contract. Polymorphic dispatch routes each call to a concrete implementation. Adding behavior then means adding an implementation, which the caller never sees.

This inverts the usual dependency direction: high-level code depends on the abstraction rather than on concrete classes, which is the same move the Dependency Inversion Principle formalizes. In a class diagram it shows up as a hollow triangle pointing up from each implementation to the contract — a dashed realization arrow when the contract is an interface (as in the examples below), a solid generalization arrow when it is an abstract class. See generalization for both, including the realization notation.

Worked example: payment processing

A checkout service that branches on payment type is the canonical OCP violation. Every new payment method reopens the same function:

function processPayment(order: Order, method: string): Receipt {
  switch (method) {
    case "card":
      return chargeCard(order);        // validate card, call gateway
    case "paypal":
      return redirectToPaypal(order);
    case "bank-transfer":
      return createTransferReference(order);
    // next sprint: case "gift-card", then "crypto", then...
    default:
      throw new Error("Unknown payment method: " + method);
  }
}

The function is closed to extension: supporting gift cards means editing — and re-testing — the code path that handles live card payments. The refactoring extracts the varying behavior behind a contract:

interface PaymentMethod {
  charge(order: Order): Receipt;
}
 
class CardPayment implements PaymentMethod {
  charge(order: Order): Receipt {
    // validate card, call gateway
    return this.gateway.charge(order.total, this.card);
  }
}
 
class GiftCardPayment implements PaymentMethod {
  charge(order: Order): Receipt {
    return this.redeem(order.total, this.cardCode);
  }
}
 
function processPayment(order: Order, method: PaymentMethod): Receipt {
  return method.charge(order); // never edited again
}

processPayment is now closed against this axis of change. Each new payment method is a new class with its own tests; the checkout flow and every existing method remain untouched.

Note what did not disappear: somewhere, the string "gift-card" from the request still has to become a GiftCardPayment instance. The conditional collapses into a single creation site — exactly the problem Factory Method exists to solve. One small, isolated place changes per new method instead of every branch point in the domain logic.

Patterns as OCP machinery

Several classic design patterns are best understood as prefabricated OCP mechanisms:

PatternWhat variesHow extension happens
StrategyAn algorithm or policy (pricing, routing)New strategy class, injected at runtime
Factory MethodWhich concrete class gets createdNew creator or registry entry
ObserverWho reacts to an eventNew subscriber; the publisher is never edited

Observer is a particularly clean case: the order-placed event publisher stays closed while inventory, email, and analytics subscribers are added as new code.

The honest cost

Every abstraction point is a bet. You are predicting where change will strike, and paying up front: an extra interface, an extra file per variant, one more hop when someone debugs the code. When the bet is right, changes become cheap and safe. When it is wrong, you carry the indirection forever and the next real change cuts across your interface anyway — now you edit the contract and every implementation, which is worse than the switch statement was.

This is why "abstract everything" fails. The useful heuristic is:

Concretely: it is usually cheaper to refactor a switch statement into an interface when the second or third case arrives than to speculate interfaces everywhere on day one. This is heuristic advice, not a formal rule — plugin architectures and published APIs justifiably create extension points before variation appears, because external consumers cannot wait for your refactoring.

Common mistakes

  • Interface-for-everything. An interface with exactly one implementation, mirroring its methods one-to-one, protects nothing and taxes every reader. OCP is about variation, and one of anything does not vary.
  • Treating OCP as never-edit-code absolutism. Fixing a bug, renaming, or refactoring existing code is not a violation. OCP targets a specific event: new behavioral requirements forcing edits to stable modules.
  • Extension points nobody uses. Hooks, plugin registries, and template methods added "just in case" are speculation in its purest form. If a seam has had one occupant for two years, inline it.
  • Hiding a responsibility problem. If a class keeps changing for unrelated reasons, the fix is usually the Single Responsibility Principle — split it — not an extension point bolted onto a class that should not exist in that shape.

Reach for it

  • A change of the same kind has recurred and each time forced edits to working code
  • Two or more concrete implementations of a behavior already exist or are firmly scheduled
  • You are publishing a plugin point that external teams will implement

Avoid it

  • The variation is imagined rather than visible in the change history
  • There is one implementation and no concrete second one in sight
  • The abstraction would mirror a single class method-for-method with no behavioral difference

Practice

Take this notification dispatcher and refactor it to satisfy OCP: extract a NotificationChannel interface with a send(message, recipient) operation, implement EmailChannel and SmsChannel, and isolate channel selection in one factory function. Then add a PushChannel and verify you touched only two things: one new class and one line in the factory.

public void notify(String channel, String message, User recipient) {
    if (channel.equals("email")) {
        smtpClient.send(recipient.getEmail(), message);
    } else if (channel.equals("sms")) {
        smsGateway.send(recipient.getPhone(), message);
    }
}

Draw the resulting class diagram. Because NotificationChannel is an interface, the arrows from EmailChannel and SmsChannel are realization arrows (dashed lines with a hollow triangle at the interface), not generalization — if you are unsure of the notation, review class diagrams first.