Skip to content
DiaGO

Dependency Inversion Principle

High-level policy should not depend on low-level detail - both should depend on abstractions. The principle behind testable, swappable architectures.

The Dependency Inversion Principle (DIP) has two clauses, as stated by Robert C. Martin:

  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.

"High-level" here means policy: the business rules that make your system worth building - order pricing, loan eligibility, booking conflicts. "Low-level" means mechanism: databases, HTTP clients, message brokers, file systems. The naive dependency direction - policy calling mechanism directly - couples the most valuable code in your system to the most volatile. DIP flips that arrow.

The arrow flip

Consider an order service that persists orders. Without inversion, the source-code dependency points from policy to detail:

Before:  OrderService --> PostgresOrderRepository
         (policy)         (detail)
 
After:   OrderService --> OrderRepository <-- PostgresOrderRepository
         (policy)         (abstraction,       (detail: implements
                          owned by policy)     the abstraction)

At runtime, control still flows from OrderService into Postgres code - that never changes. What inverts is the source-code dependency: PostgresOrderRepository now depends on an interface defined by the high-level side, and the high-level side depends on nothing below it. In UML dependency notation, the dashed arrow from the detail now points up toward the abstraction.

The "before" version in TypeScript:

// order-service.ts — policy hard-wired to a detail
import { PostgresOrderRepository } from "../infrastructure/postgres-order-repository";
 
export class OrderService {
  private repo = new PostgresOrderRepository();
 
  async placeOrder(order: Order): Promise<void> {
    // pricing, validation, business rules...
    await this.repo.save(order);
  }
}

And after inversion:

// domain/order-repository.ts — the abstraction lives WITH the policy
export interface OrderRepository {
  save(order: Order): Promise<void>;
  findById(id: OrderId): Promise<Order | null>;
}
 
// domain/order-service.ts — depends only on the abstraction
export class OrderService {
  constructor(private readonly repo: OrderRepository) {}
 
  async placeOrder(order: Order): Promise<void> {
    // business rules...
    await this.repo.save(order);
  }
}
 
// infrastructure/postgres-order-repository.ts — detail depends upward
import { OrderRepository } from "../domain/order-repository";
 
export class PostgresOrderRepository implements OrderRepository {
  async save(order: Order): Promise<void> { /* SQL here */ }
  async findById(id: OrderId): Promise<Order | null> { /* SQL here */ }
}

DIP is not dependency injection

The two are constantly conflated because they usually appear together. They are different things:

Dependency inversion (DIP)Dependency injection (DI)
What it isA design principle about the direction of source-code dependenciesA construction technique: collaborators are supplied from outside instead of created internally
The question it answersWho owns the abstraction, and which module depends on whichHow an object obtains its dependencies at runtime
Independent of the other?Yes - you can satisfy DIP and wire implementations with a factory instead of a containerYes - injecting a concrete PostgresOrderRepository is DI, but inverts nothing

DI is one convenient way to implement DIP: since OrderService can no longer instantiate its repository (that would reintroduce the dependency), something outside must hand it one. But a DI container full of concrete types satisfies the letter of injection while violating the principle entirely.

What it buys you

Testability. OrderService can be exercised against an in-memory fake repository - no database, no containers, millisecond-fast tests of the actual business rules.

Swappable infrastructure. Moving from Postgres to DynamoDB, or adding a second payment gateway, means writing a new implementation of an existing interface. The policy code does not change - this is the same mechanism that makes the Open-Closed Principle achievable in practice.

Clean layering. DIP is the load-bearing idea in layered architecture and its hexagonal variant: it lets the domain layer sit at the center with every dependency arrow pointing inward, so infrastructure can be developed, replaced, and deployed independently of the rules it serves.

What it costs

Be honest about the price. Every inverted dependency adds an interface, an extra file, and a level of indirection between "who calls" and "what runs" - navigation and debugging get slightly harder. In many codebases most such interfaces have exactly one production implementation, and that is normal, not a smell: the second implementation is usually the test fake. But in a small, stable module where you would never swap the dependency and can test through it comfortably, the interface is ceremony you are allowed to skip. DIP is heuristic design advice about volatile boundaries, not a rule that every class needs an interface.

Reach for it

  • The dependency crosses an architectural boundary such as domain to database or domain to external API
  • You need to substitute a fake or in-memory implementation to test business rules in isolation
  • You realistically expect to swap or multiply the detail, such as adding a second payment provider

Avoid it

  • Stable dependencies on the standard library or core language types
  • Small scripts and prototypes where the indirection costs more than it protects
  • Pure deterministic domain logic that has no side effects and needs no substitute

Common mistakes

Interface owned by the low-level module. Covered above, and worth repeating: an interface in the infrastructure package, mirroring the vendor API method-for-method, inverts nothing.

Leaky abstractions. An OrderRepository whose methods accept SQL fragments, return ORM entities, or throw vendor-specific exceptions has smuggled the detail through the interface. Every caller is now coupled to the technology anyway - you paid the indirection cost and got none of the benefit.

Inverting everything. Injecting a TaxCalculator that is a pure function, or abstracting over Math.round, adds interfaces where there is no volatility and nothing to fake. Point the ceremony at real boundaries.

Practice

Take this class and invert its dependencies: a BookingReminderService that directly instantiates SmtpMailer (sends email via a specific SMTP library) and MySqlBookingStore (loads tomorrow's bookings with raw SQL). Define the abstractions the service needs - name them and place them on the high-level side - then write an in-memory fake for each and a unit test proving that a booking starting tomorrow triggers exactly one reminder. Check your interfaces for leaks: no SQL strings, no SMTP types, no vendor exceptions should appear in their signatures. Sketch the result as a small class diagram and confirm every arrow from a detail points toward an abstraction.