Dependency Inversion

Term side of the Card.
Topic: Architecture
Unit title: Dependency Inversion
Categories: Concept
Explanation side of the Card

Explanation: 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.

Example

Wrongts
import { PostgresClient } from './postgres';

class OrderService {
  private db = new PostgresClient();
  async place(order: Order) {
    await this.db.insert('orders', order);
  }
}
Rightts
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.

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