Open-Closed
ELI5 — The Vibe Check
Open-Closed means your code should be open for adding new features but closed for editing old working code. Like a power strip — you can plug in new devices without rewiring the wall socket. Add new behavior by extending, not by hacking into existing code.
Real Talk
The Open-Closed Principle states that software entities should be open for extension but closed for modification. New functionality is added by creating new classes or methods rather than modifying existing ones, typically achieved through abstractions, interfaces, and inheritance.
Show Me The Code
// Closed for modification, open for extension
interface DiscountStrategy {
calculate(price: number): number;
}
class SummerDiscount implements DiscountStrategy {
calculate(price: number) { return price * 0.8; }
}
class BlackFridayDiscount implements DiscountStrategy {
calculate(price: number) { return price * 0.5; }
}
When You'll Hear This
"Adding a new payment method shouldn't require editing the checkout class." / "Follow Open-Closed and you'll never break existing tests adding new features."
Related Terms
Dependency Inversion
Dependency Inversion says high-level code shouldn't depend on low-level code — both should depend on abstractions.
Polymorphism
Polymorphism means the same method call can do different things depending on which object it's called on. Call 'speak()' on a Dog and you get a bark.
SOLID (SOLID)
SOLID is five rules for writing code that doesn't turn into a nightmare over time. Each letter stands for a different rule.
Strategy Pattern
You're writing a sorter and want to sort by price, name, or date depending on user choice.