SteelReed

Search

Search posts, questions…

OOP & DesignQuestion 11 / 42

Middle

What is the Open/Closed Principle? Is it always good, and how does it relate to Dependency Inversion?

Short answer

OCP: a module is open for extension, closed for modification; add behavior by adding a new class instead of editing code that already works. The way to get there is to depend on an abstraction and plug in new implementations, usually through Strategy.

Fee calculation codeFeePolicy interfaceExisting policyNew policy:new class, old codeuntouched

3 points to say:

  1. OCP: add behavior with new code, don't edit code that already works.
  2. Achieved with DIP + Strategy, not inheritance.
  3. "Close" only at variation points you have actually seen; two cases is a switch, refactor at the third case.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.