Dependency Inversion

Make important code depend on an abstraction (an interface describing what it needs) instead of one concrete implementation.

What is it?

Imagine an OrderService that, deep in one method, creates a new PostgresDatabase() and calls .save() on it. Harmless-looking, but OrderService is now welded to Postgres. A fast unit test of the order logic needs a real Postgres connection. Switching databases or mocking storage means editing OrderService, even though its logic didn't change.

Dependency inversion flips this. OrderService depends on an abstraction, like an OrderRepository interface that just means "something with a .save(order) method". The concrete PostgresDatabase implements that interface. Now OrderService doesn't care whether it talks to Postgres, an in-memory fake, or anything else. It only knows the shape it depends on.

"Inversion" is about which way the dependency points. Normally the high-level business logic depends on the low-level database detail. Here, both depend on a shared abstraction between them.

Explain like I'm 10

A lamp doesn't care whether its power comes from coal, solar, or wind. It just needs a standard wall socket. The socket is the abstraction: any source that fits can be swapped in without rewiring the lamp.

Examples

Before: business logic depends on a concrete class

class PostgresDatabase {
  save(order) {
    // real SQL insert
  }
}

class OrderService {
  constructor() {
    this.db = new PostgresDatabase(); // hard-wired to one concrete class
  }
  placeOrder(order) {
    // ...business rules...
    this.db.save(order);
  }
}

// Testing this requires a real (or heavily mocked) Postgres connection.
const service = new OrderService();

OrderService creates and depends on PostgresDatabase directly. You can't swap in a fake for testing without editing OrderService.

After: business logic depends on an abstraction

// The abstraction both sides depend on
class OrderRepository {
  save(order) { throw new Error("not implemented"); }
}

class PostgresOrderRepository extends OrderRepository {
  save(order) { /* real SQL insert */ }
}

class InMemoryOrderRepository extends OrderRepository {
  constructor() { super(); this.orders = []; }
  save(order) { this.orders.push(order); }
}

class OrderService {
  constructor(repository) {
    this.repository = repository; // depends on the abstraction, injected from outside
  }
  placeOrder(order) {
    // ...business rules...
    this.repository.save(order);
  }
}

// Production
const service = new OrderService(new PostgresOrderRepository());

// Test — no real database needed
const testService = new OrderService(new InMemoryOrderRepository());

OrderService no longer knows Postgres exists. Tests swap in an InMemoryOrderRepository without changing OrderService, so the business logic is checked in isolation.

How it works

Dependency inversion has two halves that are easy to mix up:

- Define an abstraction (an interface, or in JavaScript often just an agreed set of methods) that captures only what the high-level code needs. - Inject the concrete implementation from outside, usually through a constructor or function parameter, instead of letting the high-level code create it.

Injection is what makes the swap possible. An abstraction alone doesn't help if the code still hard-codes which implementation to build.

Why does it exist?

It solves two costly problems at once:

- Untestable business logic, welded to a real database, network, or filesystem. - Rigid systems, where switching a storage engine, payment provider, or library means rewriting core logic instead of writing a new implementation of an existing abstraction.

When to use it

Apply it where core logic meets something volatile, slow, or hard to test alone: databases, third-party APIs, the filesystem, the current time, randomness. If a test is blocked by "that would need a real X", dependency inversion probably belongs there.

When not to use it

An abstraction plus injection for something with only one implementation that's easy to test (e.g., a pure math utility) adds indirection that buys nothing. Save it for real seams, where substitution is plausible or testing is otherwise blocked.

Common mistakes

  • Creating an interface for every class 'for flexibility', even ones with only one implementation that never needs swapping.

  • Designing the abstraction around the low-level implementation (mirroring what Postgres offers) instead of what the high-level logic needs.

  • Still constructing the concrete dependency inside the high-level class (e.g., new PostgresOrderRepository() in OrderService's constructor). That recreates the tight coupling even though an interface exists.

Practice exercises

  1. Easy:

    Change a class that calls fetch() directly for weather data so it depends on an injected WeatherClient abstraction instead.

  2. Medium:

    Write an in-memory fake of an EmailSender abstraction so you can unit test a NotificationService without sending real emails.

  3. Hard:

    Design a PaymentGateway abstraction for a checkout service so that swapping between two real payment providers (and a test fake) needs zero changes to the checkout service. List the methods it needs.

Interview questions

What is dependency inversion?

A principle where high-level code depends on an abstraction (like an interface) instead of a concrete low-level implementation. The implementation also depends on that abstraction, inverting the naive direct dependency.

How does dependency inversion improve testability?

A test can swap a fake or in-memory implementation in for the real one (e.g., a real database), so business logic runs in isolation, quickly and deterministically.

What's the difference between dependency inversion and dependency injection?

Dependency inversion is the principle (depend on abstractions, not concretions). Dependency injection is the technique of supplying a dependency from outside, like a constructor parameter, which makes the inversion possible in practice.