Open/Closed Principle

OCP

“Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.” – Bertrand Meyer

The goal is to be able to extend the behavior of a system without modifying existing code, which prevents the introduction of new bugs in already working code.

When to use

Use OCP when you have algorithms or behaviors that vary (e.g., different payment methods, different report formats) and you expect new variations to be added in the future.

Why it matters

  • Stability: You don’t risk breaking existing functionality when adding new features.
  • Maintainability: New code is added in new files/classes, keeping existing code simple and untouched.

Signs of Violation

  • You have to edit a switch or if/else statement in a core class every time you add a new type or feature.
  • A class has a list of “supported types” hardcoded inside it.

Explanation

Problem

If you have to modify a class every time a new requirement comes in (e.g., adding a new tax calculation rule), you risk breaking the class for existing rules.

Solution

Use polymorphism (interfaces or abstract classes) to allow different implementations to be swapped in. The main code depends on the abstraction and doesn’t need to change when a new implementation is created.

Real world analogy

A power strip is designed to accept any device with a standard plug. You can “extend” the power strip’s utility by plugging in a lamp, a TV, or a charger, without having to unscrew the power strip and rewire it (modify it).

Pros and Cons

Pros Cons
  • Reduces regression bugs
  • Encourages flexible design
  • Can increase complexity (more classes)
  • Requires careful design of interfaces
  • Comparison

    • Strategy Pattern: Often used to implement OCP.
    • Polymorphism: The mechanism that enables OCP.

    Code example

    Typescript

    Bad (Violation)

    Good (Adherence)

    PHP

    Bad (Violation)

    Good (Adherence)