# Dependency Inversion

> The Dependency Inversion is a principle stating that high-level modules should not depend on low-level modules; both should depend on abstractions.

## What is the Dependency Inversion Principle?

The principle emphasizes that high-level business logic should not rely on low-level implementation details. Instead, both should depend on abstract interfaces, allowing for greater flexibility and easier modification of components.

- Topic: Architecture
- Type: concept

## Example

Wrong:

```ts
import { PostgresClient } from './postgres';

class OrderService {
  private db = new PostgresClient();
  async place(order: Order) {
    await this.db.insert('orders', order);
  }
}
```

Right:

```ts
interface OrderRepo {
  save(order: Order): Promise<void>;
}

class OrderService {
  constructor(private orders: OrderRepo) {}
  async place(order: Order) {
    await this.orders.save(order);
  }
}
```

`OrderService` depends on the `OrderRepo` contract, so storage can change or be faked in tests.

## Common mistakes

- Creating a database client inside a service, so the service can't be tested without a real database.

## Key points

- Business logic receives its dependencies through the constructor or parameters, not `new` inside it.
- The interface is owned by the high-level module and named for its need, like `OrderRepo`.
- Tests pass a fake implementation instead of mocking module imports.

## Interview questions

### Dependency inversion vs dependency injection: what's the difference?

Inversion is the principle: depend on abstractions. Injection is a technique: pass dependencies in from outside, which is the usual way to apply it.

### Do I need a DI container?

No. Passing dependencies through constructors or function parameters is enough for most apps; containers help only in large codebases.

## Related cards

- [SOLID](https://wonderium.dev/engineering/solid.md)
- [Abstraction](https://wonderium.dev/engineering/abstraction.md)
- [Mocks](https://wonderium.dev/engineering/mocks.md)
- [Three-Layer Architecture](https://wonderium.dev/engineering/three-layer-architecture.md)
- [interface](https://wonderium.dev/ts/interface.md)

---

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