SOLID Principlescritical

Open/Closed Principle (OCP)

Software entities should be open for extension but closed for modification — you add new behaviour by adding new code, not by editing existing code.

Memory anchor

OCP = a power strip. You plug in new devices (extension) without rewiring the wall (modification). The outlet is closed for renovation but open for new appliances.

Expected depth

OCP is achieved primarily through polymorphism: define an abstraction (interface or abstract class), and introduce new behaviour by implementing or extending it. A payment processor with a giant switch-case over payment types violates OCP — each new payment type requires modifying the switch. Replace it with a PaymentStrategy interface; each payment type is a new class that the client never touches.

Deep — senior internals

OCP has a nuanced caveat: it is impossible to close a module against all types of change. Bertrand Meyer's original formulation was about inheritance; Robert Martin reinterpreted it for polymorphism. The key insight is: anticipate the axes of variation (what is likely to change?) and close against those. Do not over-abstract: premature closures add indirection with no payoff. The pattern vocabulary that most directly enforces OCP is Strategy (behaviour variation), Decorator (feature variation), and Template Method (algorithm skeleton variation). OCP also interacts with the Dependency Inversion Principle: to be closed against change, a module must depend on stable abstractions, not volatile concretions.

🎤Interview-ready answer

OCP means: when requirements change, I want to add a new class rather than edit an existing one. If I'm building a report generator that supports PDF and CSV today, I define a ReportFormatter interface and have PdfFormatter and CsvFormatter implement it. Tomorrow, when Excel support arrives, I write ExcelFormatter — the generator never changes. The violation would be a method full of if-else or switch blocks that I must reopen every time.

Common trap

Do not claim OCP means you never modify code — you always modify code to add the abstraction in the first place. OCP applies to stable modules: once a module is well-used and tested, protect it from change. Also, over-applying OCP produces needless abstraction for things that will never vary.

Related concepts