Open/Closed Principle (OCP)
MediumIn plain terms
The Open/Closed Principle says you should be able to add new behavior without changing existing, working code. "Open for extension" means you can extend (e.g. new subclass, new implementation). "Closed for modification" means you do not have to edit existing classes to add that behavior.
Why? Changing existing code risks breaking current behavior and forces retesting. By extending—new classes, new implementations of an interface—you add features without touching the old code. Use abstractions (interfaces, abstract classes) so new behavior plugs in without modifying the core logic.
What you need to know
- •Open for extension
- •Closed for modification
- •Use abstractions to plug in new behavior
Example
Code is language-agnostic in spirit; adapt the idea to your language:
// Closed: PaymentProcessor doesn't change
// Open: add new payment type by adding new class
class PaymentProcessor {
process(payment) {
return payment.charge(); // abstraction
}
}
class CreditCardPayment { charge() { /* ... */ } }
class PayPalPayment { charge() { /* ... */ } }
// New type = new class, no edit to PaymentProcessorWhy this matters
OCP is central to extensible design. Interviewers ask how you add features without modifying existing code—abstractions and polymorphism are the answer.
How it connects
Achieved via abstractions (interfaces, abstract classes) and polymorphism: new behavior = new implementation, not edits to old code. DIP (depend on abstractions) supports OCP; LSP ensures subtypes do not break the contract.
Interview focus
Be ready to explain these; they come up often.
- ▸"Open for extension, closed for modification." Add new classes, do not edit existing ones.
- ▸How: depend on interfaces/abstractions; new behavior = new class implementing the interface.
- ▸Example: new payment type = new class, not changing PaymentProcessor.
Learn more
Dive deeper with these resources: