Skip to content
Velloreth
Programming 6 min read

The Dependency Inversion Principle Explained

Dependency inversion says high-level policy should not depend on low-level detail. Learn what that means in practice and why it makes code testable.

By

The principle

The dependency inversion principle has two parts:

  1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
  2. Abstractions should not depend on details. Details should depend on abstractions.

The name comes from the second part. In a conventional layered design, the high-level policy depends on the low-level detail, so the dependency arrow points from policy to detail. Inverting it means both point at an abstraction, and the detail implements it.

The problem it solves

Consider a service that places orders.

class OrderService {
  private db = new MySQLDatabase();

  placeOrder(order: Order) {
    this.db.insert('orders', order);
  }
}

OrderService is the high-level policy — it knows the business rule about placing orders. MySQLDatabase is the low-level detail — it knows SQL.

The dependency arrow points from policy to detail. Three consequences follow:

The policy is welded to the detail. Switching to Postgres means editing OrderService.

The policy cannot be tested alone. Every test needs a real MySQL instance.

The detail’s concerns leak upward. If the database client changes its API, the business logic must change.

The inverted design

Define the interface the policy needs, and have the detail implement it.

// The policy defines what it needs
interface OrderRepository {
  save(order: Order): Promise<void>;
}

class OrderService {
  constructor(private repository: OrderRepository) {}

  async placeOrder(order: Order) {
    await this.repository.save(order);
  }
}

// The detail implements the policy's interface
class MySQLOrderRepository implements OrderRepository {
  async save(order: Order) {
    await this.db.insert('orders', order);
  }
}

Now the dependency arrow points from MySQLOrderRepository to OrderRepository, which is owned by the policy layer. The detail depends on the policy, not the other way around. That is the inversion.

Who owns the interface

This is the detail people miss, and it is the part that makes the principle work.

The interface must be owned by the high-level module. If the database layer defines OrderRepository and the service imports it, the service still depends on the database layer — the arrow has not moved.

The test: if you deleted the database module entirely, would the service still compile? With the interface owned by the service, yes. With the interface owned by the database, no.

In practice this means the interface lives in the same package or module as the policy, and the implementation lives elsewhere.

The payoff: testability

The most immediate benefit is that the policy can be tested without the detail.

class FakeOrderRepository implements OrderRepository {
  public saved: Order[] = [];
  async save(order: Order) { this.saved.push(order); }
}

test('placeOrder saves the order', async () => {
  const repo = new FakeOrderRepository();
  const service = new OrderService(repo);

  await service.placeOrder({ id: '1', total: 100 });

  expect(repo.saved).toHaveLength(1);
  expect(repo.saved[0].id).toBe('1');
});

The test runs in microseconds, needs no database, and cannot fail because of network conditions. That is the practical value of inversion, and it is why the principle is worth learning even if you never use a DI container.

The composition root

If everything depends on abstractions, something must eventually create the concrete objects. That place is the composition root.

// main.ts — the composition root
const config = loadConfig();
const db = new MySQLDatabase(config.databaseUrl);
const repository = new MySQLOrderRepository(db);
const service = new OrderService(repository);

app.post('/orders', (req, res) => service.placeOrder(req.body));

This is the only place that knows about MySQLDatabase and MySQLOrderRepository. Everything else works with interfaces. Swapping the database means editing this one file.

The composition root is usually at the application’s entry point. Keeping it small and central is what makes the rest of the codebase testable.

Inversion without a container

A common misconception is that dependency inversion requires a framework. It does not.

// Plain constructor injection — no container
const service = new OrderService(new MySQLOrderRepository(db));

That is the whole technique. A container automates the wiring for large applications, but the principle is satisfied by passing dependencies in.

Containers become useful when the object graph is deep and the wiring is repetitive. For a small application, manual wiring in the composition root is clearer and has no magic.

Where the principle applies

Database access. The policy defines a repository interface; the data layer implements it.

External APIs. The policy defines a client interface; the HTTP implementation lives at the edge.

Time and randomness. The policy defines a clock or a random source; the real implementation is injected. This makes time-dependent logic testable.

Logging. The policy defines a logger interface; the concrete logger is injected.

File systems. The policy defines a storage interface; the local and S3 implementations both satisfy it.

Message queues. The policy defines a publisher interface; the broker implementation is swappable.

The pattern in every case: the policy declares what it needs, and the detail conforms.

When not to invert

Stable, simple dependencies. Depending on the standard library’s Math or a language’s string type is fine. Inverting everything produces absurdity.

Value objects. A Money or Email class is a detail the policy can depend on directly. It is not an external dependency.

Small scripts. A 100-line script does not need a composition root and five interfaces.

When the abstraction is speculative. An interface with one implementation and no test double is ceremony. Add it when the second implementation or the first fake appears.

The judgement: invert dependencies that are external, likely to change, or need to be faked. Leave the rest alone.

Common mistakes

Defining the interface in the wrong layer. If the low-level module owns it, nothing is inverted.

Leaking detail through the interface. An interface with a query(sql: string) method is not an abstraction — it is SQL with extra steps. The interface should express what the policy needs, not how the detail works.

Injecting the container. Passing the DI container into a class hides its dependencies, which defeats the purpose. Inject the specific dependencies.

One interface per class. Not every class needs an interface. Only the ones at boundaries.

Confusing inversion with injection. Injection is a technique; inversion is the design goal.

Practical guidance

  • Define interfaces in the policy layer, not the detail layer.
  • Inject dependencies through constructors rather than creating them inside.
  • Keep a single composition root at the application entry point.
  • Write fakes for the interfaces you define, and use them in tests.
  • Do not invert stable, simple dependencies.
  • Express policy needs in the interface, not the detail’s API.
  • Skip the container until manual wiring becomes painful.

For the related principles, see SOLID principles explained and interfaces vs abstract classes. For the practical technique, dependency injection without a framework and design patterns for beginners.

Quotable summary

The dependency inversion principle says high-level policy should not depend on low-level detail; both should depend on abstractions, and the abstraction should be owned by the high-level module so the dependency arrow points inward. In practice it means depending on interfaces you define rather than on concrete classes you import, and the main payoff is testability, because a class depending on an interface can be tested with a fake and no database or network. It is not the same as dependency injection: inversion is the design goal, injection is one technique for achieving it, and plain constructor parameters satisfy the principle without any framework. A single composition root creates the concrete objects at startup, and everything else works with abstractions.

Frequently asked questions

What is the dependency inversion principle in simple terms?
It says that important business logic should not be tied to specific technical details like a particular database or HTTP client. Instead, both should depend on an interface, so the detail can be swapped without changing the logic.
What is the difference between dependency inversion and dependency injection?
Inversion is the design principle: depend on abstractions, not concretions. Injection is a technique for supplying those dependencies from outside. You can inject without inverting, and you can invert without a container.
Who should own the interface?
The high-level module should own it. If the business logic defines the interface it needs, the low-level module implements it, and the dependency points inward toward the policy. If the low-level module defines it, the dependency still points outward and nothing is inverted.
Does dependency inversion require a framework?
No. You can do it with plain constructor parameters. A dependency injection container automates the wiring, but the principle is about where the dependency points, not about tooling.
Is dependency inversion always worth it?
No. For a small script or a stable, simple dependency, an interface adds ceremony. It pays off when the dependency is external, likely to change, or needs to be faked in tests.
What is a composition root?
The composition root is the single place in an application where concrete implementations are created and wired together, usually at startup. Everything else depends on abstractions, and only the root knows the concrete types.