Course contentsShow
← Python
Lesson 485 of 1,0607. Object-Oriented ProgrammingFree lesson

Building Decoupled Systems with Dependency Injection

Learn to pass dependencies into class constructors to improve testability and reduce tight coupling between disparate modules in your application.

In this lesson, you will learn how to reduce tight coupling in your code by passing dependencies directly into class constructors instead of hardcoding them inside the class.

The Problem: Tight Coupling

When a class is responsible for creating its own dependencies, it becomes "tightly coupled" to those specific implementations. Consider a ReportGenerator that creates its own EmailService internally:

class ReportGenerator:
    def __init__(self):
        # Tight Coupling: The generator is forced to use the real EmailService
        self.service = EmailService() 

    def send(self, data):
        self.service.send(data)

This design makes testing difficult. If you want to unit test the ReportGenerator, you are forced to trigger actual emails because you cannot easily swap EmailService for a mock object.

The Solution: Dependency Injection (DI)

Dependency Injection is the practice of "injecting" a required object into a class via its constructor. By requiring the dependency as an argument, the class no longer cares how the service is created or what its concrete implementation is—it only cares that the object conforms to the expected interface.

class ReportGenerator:
    # We inject the service dependency via the constructor
    def __init__(self, service):
        self.service = service

    def send(self, data):
        self.service.send(data)

Why This Matters

By shifting the responsibility of creation outside the class, you gain several benefits:

  1. Testability: During testing, you can pass a "Mock" or "Dummy" service into the constructor, allowing you to verify logic without side effects like sending real emails or hitting production databases.
  2. Flexibility: You can swap components at runtime. If you decide to switch from EmailService to SMSService, you simply pass a different object into the constructor without modifying a single line of the ReportGenerator code.
  3. Decoupling: Your classes become modular components that depend on abstractions rather than rigid, concrete implementations. This is a core pillar of writing maintainable, scalable software.

Key Takeaway: By passing dependencies into a constructor, you transform rigid, hard-to-test code into a flexible, modular system where objects define their requirements rather than dictating their implementation.