All topics
SOLID principles
intermediate

Open/Closed Principle (OCP)

Software entities should be open for extension, but closed for modification.

The Open/Closed Principle holds that software entities — classes, modules, functions — should be open for extension but closed for modification. You should be able to add new behaviour by adding new code, not by editing existing, already-tested, already-deployed code. The motivation is risk: every change to working code is a chance to introduce a regression, so the ideal is to grow a system by addition rather than by surgery.

A power outlet is closed for modification — you don't rewire the wall to use a new appliance. But it's open for extension — any device with the right plug works.

Key Concepts

1
The smell that signals a violation is a conditional that you have to keep reopening: an if/else or switch on a type code that grows a new branch every time a new variant appears — a new payment method, a new shape, a new report format. Each addition forces you back into the same method, re-testing everything around it. The standard remedy is polymorphism behind a stable abstraction. Define an interface (PaymentMethod, Shape), have the existing code depend only on that interface, and add each new variant as a new implementing class. The original code never changes; it is closed. The set of behaviours is open, extended by dropping in new classes. Strategy, Template Method, and dependency injection are the usual mechanisms for achieving this.
if/elseswitchPaymentMethodShape
2
The honest caveat, and a good interview point, is that you cannot make everything open to every kind of change, and trying to do so produces speculative, over-abstracted designs riddled with interfaces nobody needs. The pragmatic approach is to identify the axis of change that is actually likely for this part of the system — the dimension along which new variants keep arriving — and design the abstraction to absorb that, while accepting that genuinely unforeseen changes may still require modification. OCP is about anticipating the right variation, not all variation.