Open-Closed

Term side of the Card.
Topic: Architecture
Unit title: Open-Closed
Categories: Concept
Explanation side of the Card

Explanation: The principle that ensures classes and functions are designed to allow their behavior to be extended without altering their existing implementation. This facilitates the addition of new functionality while preserving the stability of the system.

Example

Wrongts
function shippingCost(method: string, weight: number) {
  if (method === 'standard') return weight * 1;
  if (method === 'express') return weight * 3;
  throw new Error('Unknown method');
}
Rightts
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 if for 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/switch chain.
  • 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.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy