Dependency Inversion Principle
You'll learn to
- -Explain Dependency Inversion as "both sides depend on an agreed contract", with a plug-and-socket picture
- -Show how it lets you test a service with an in-memory fake and no database
- -Tell Dependency Inversion (a principle) apart from Dependency Injection (a technique)
Tip: the highlighter is on - just select any text below to mark it. Use the highlighter button up top to change color or turn it off. Highlights are saved on this device only. Log in to save them to your account instead.
The Dependency Inversion Principle (DIP) says high-level code should not depend on low-level code. Both should depend on an abstraction, a contract that hides the details. High-level code is the code that decides what should happen, such as an OrderService with the rules for placing an order. Low-level code handles a detail of how, such as MySQLOrderRepository, which talks to one particular database.
An Analogy: A Lamp With and Without a Plug
A lamp whose cord is wired permanently into the wall can only ever use that wall, and you cannot test the lamp without going to the wall. A lamp with a plug and a standard socket works anywhere that offers the socket, and in a test you can plug it into a battery. The socket is the abstraction. Neither the lamp nor the wall depends on the other. Both depend on the agreed plug shape.
Why "Inversion"?
Without DIP the dependency arrow points from the high-level code down to the detail. OrderService creates a MySQLOrderRepository itself. That means you cannot test OrderService without a real database, and you cannot reuse it with different storage without editing it. DIP turns the arrow around. OrderService states the contract it needs, OrderRepository, and the MySQL class is written to fit that contract. The detail now depends on the policy, not the other way round.
# Before: OrderService is tightly coupled to a concrete, low-level detail
class OrderService:
def __init__(self):
self._repo = MySQLOrderRepository() # concrete dependency baked in
# After: both depend on an abstraction; OrderService owns the contract shape
class OrderRepository(ABC):
@abstractmethod
def save(self, order: Order) -> None: ...
class MySQLOrderRepository(OrderRepository):
def save(self, order: Order) -> None: ... # low-level detail
class InMemoryOrderRepository(OrderRepository):
def save(self, order: Order) -> None: ... # trivial to swap in for tests
class OrderService:
def __init__(self, repo: OrderRepository): # depends on the abstraction
self._repo = repoThe demo below puts that into practice. The service asks for any OrderRepository, and in this "test" we give it a tiny in-memory one. No database or network is involved, yet we can check that valid orders are saved and invalid ones are rejected.
Dependency Inversion vs. Dependency Injection
These two terms sound alike and interviewers notice when they are mixed up. Dependency Inversion is the design principle: depend on abstractions, not on concrete details. Dependency Injection is a technique: pass a dependency into a class from outside (through the constructor, a method or a setter) instead of building it inside. In the demo, OrderService(repo) is injection.
You can use injection without inversion. If you inject a MySQLOrderRepository object into a service that is typed to require exactly that class, the service still depends on the detail. You get the real benefit, testability and swappability, only when you combine the two: inject something typed as the abstraction.
DIP is the payoff for every earlier "design to the interface" habit in this course. It is the formal name for that instinct, applied to how high-level policy and low-level detail relate.
How would you explain why OrderService directly instantiating MySQLOrderRepository inside its constructor is a problem?
"It's fine as long as MySQLOrderRepository works correctly."
"It couples a high-level policy class to a low-level storage detail. OrderService can't be unit tested without a real database, and swapping storage backends means editing OrderService itself. I'd have OrderService depend on an OrderRepository interface and receive an implementation via constructor injection - that's dependency inversion plus dependency injection working together."
What does the Dependency Inversion Principle actually invert?
Discussion0
Join the Discussion
Sign in to leave comments, reply to others, or like insights.
No comments yet. Be the first to start the thread!