Open-Closed
Example
function shippingCost(method: string, weight: number) {
if (method === 'standard') return weight * 1;
if (method === 'express') return weight * 3;
throw new Error('Unknown method');
}const rates: Record<string, (weight: number) => number> = {
standard: (w) => w * 1,
express: (w) => w * 3,
};
function shippingCost(method: string, weight: number) {
const rate = rates[method];
if (!rate) throw new Error('Unknown method');
return rate(weight);
}A new method is a new entry in rates, so shippingCost itself no longer changes.
Common mistakes
- Adding another
else iffor every new case until one function knows about every variant.
Key points
- New variants are added as new entries or classes, not by editing a growing
if/switchchain. - Extension points exist only where variation is real, not on every function.
Interview questions
Does Open-Closed mean I can never edit existing code?
No. Bug fixes and refactoring are fine. It means adding a new variant shouldn't force changes to code that already works.
How is Open-Closed related to the Strategy pattern?
Strategy is a common way to follow it: each behavior is a separate object, and new ones are added without touching the caller.