What is the Open/Closed Principle, with an example?

SOLID & Design Patterns SOLID Intermediate 2–3 Yrs3–5 Yrs Architecture 1 min read

Quick Answer

A class should be open for extension but closed for modification — you add new behaviour by adding new code (a new class), not by editing tested existing code. The typical smell is a growing switch/if-else that you touch every time a new case appears.

Open/Closed says once a class is written and tested, I shouldn't have to edit it to add new behaviour — I extend it instead. The classic violation is a shipping-cost method with a big switch on the shipping type: every new option means editing and re-testing that method. The compliant version is a IShippingCalculator interface with one class per shipping type, and adding a new option is just a new class. It's mostly achieved through polymorphism and the strategy pattern.

  • Violation: decimal CalculateShipping(Order o) { switch (o.Method) { case Standard: ...; case Express: ...; } } — every new method edits this.
  • OCP-compliant: IShippingCalculator with one implementation per method; the container or a factory picks the right one. Adding “overnight” is a new class, zero edits to the old ones.
  • Achieved with polymorphism, strategy, and plugins.
  • Don't over-apply — a rule that genuinely never changes doesn't need an abstraction.