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
- Find a high-level class that creates a low-level one: OrderService creates PostgresRepository() inside itself.
- Define the interface the high-level code actually needs: OrderRepository with save(order).
- Make the low-level class implement that interface.
- Pass the implementation into the high-level class through its constructor.
- 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
- Depend on interfaces; inject the implementations (dependency injection).
- Makes testing easy with fakes and mocks.
- Lets you swap infrastructure, like the database or email provider, with no change to business logic.
- Dependency inversion is the principle; dependency injection is a technique for achieving it.
Common mistakes
- An interface that copies one vendor's API exactly, so the abstraction leaks.
- Creating dependencies inside methods 'just this once'.
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.