# Open-Closed

> The Open-Closed is a principle that software entities should be open for extension but closed for modification, adding new features without altering code.

## What is the Open-Closed Principle?

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.

- Topic: Architecture
- Type: concept

## Example

Wrong:

```ts
function shippingCost(method: string, weight: number) {
  if (method === 'standard') return weight * 1;
  if (method === 'express') return weight * 3;
  throw new Error('Unknown method');
}
```

Right:

```ts
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.

## Related cards

- [SOLID](https://wonderium.dev/engineering/solid.md)
- [Strategy](https://wonderium.dev/engineering/strategy.md)
- [Polymorphism](https://wonderium.dev/engineering/polymorphism.md)
- [Decorator](https://wonderium.dev/engineering/decorator.md)
- [Single Responsibility](https://wonderium.dev/engineering/single-responsibility.md)

---

- Level: [Engineering](https://wonderium.dev/engineering.md)
- HTML version: https://wonderium.dev/engineering/open-closed
- Last updated: 2026-11-25
