SOLID: D — Dependency Inversion Principle

High-level code should depend on abstractions, not on concrete low-level details.

Why it matters

When business logic creates its own database connection or email client, it's welded to them. You can't test it without a real database, and switching providers means rewriting business code.

The idea

If OrderService creates a MySQLDatabase directly, you can't swap the database or test without one. Instead, OrderService depends on an OrderRepository interface, and the concrete repository — MySQL in production, an in-memory one in tests — is passed in.

A standard wall socket. Your lamp depends on 'a standard socket', not on one particular power station, so you can switch energy supplier without rewiring the lamp.

Socket standards are agreed by whole countries. In code you design the abstraction yourself, and a bad one (leaking database details) gives you none of the benefits.

How it works

  1. Find a high-level class that creates a low-level one: OrderService creates PostgresRepository() inside itself.
  2. Define the interface the high-level code actually needs: OrderRepository with save(order).
  3. Make the low-level class implement that interface.
  4. Pass the implementation into the high-level class through its constructor.
  5. At start-up, connect the real pieces together. In tests, pass in fakes.

Example

OrderService(repository) uses PostgresOrderRepository in production and InMemoryOrderRepository in tests.

Key points

Common mistakes

Not true: Creating the database object inside the method that uses it keeps the code easy to test.
In fact: The method is then tied to the real database, so a test can't hand it a fake one. Pass the dependency in from outside (dependency injection).

In the interview

Dependency inversion means business logic depends on interfaces, and concrete implementations are injected. My OrderService depends on an OrderRepository interface, so I can use Postgres in production and an in-memory fake in tests.

Part of Unit 5: Low-level design: OOP and SOLID in the free System Design course.