DIP

DIP — Dependency Inversion Principle

"High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions." — Robert C. Martin, Agile Software Development (1996)


Core idea

Neither the high-level (business logic) nor the low-level (DB, network, files) part of the system should know about the other directly. Both depend on an abstraction in the middle (Protocol / ABC) that lives separately and is owned by the high-level side.


What "high-level" and "low-level" mean

High-level Low-level
Business rules, domain Infrastructure
What should happen How it is done
OrderService, CheckoutWorkflow PostgresClient, SmtpClient, S3Storage
Stable (rarely changes) Volatile (new DBs, new APIs)
Valuable (unique know-how) Replaceable (off-the-shelf libraries)

High-level is the heart of the application, what the customers pay for. Low-level is the hands and feet: today it is Postgres, tomorrow it is DynamoDB.


"Inversion" — where the name comes from

The naive structure

┌──────────────────────┐
│   CheckoutService    │  ← high-level (business)
└──────────┬───────────┘
           │ imports / creates
           ↓
┌──────────────────────┐
│   PostgresClient     │  ← low-level (DB)
└──────────────────────┘

Arrow pointing down: the business logic depends on the DB. It feels obvious. It is also bad:

The DIP structure

┌──────────────────────┐
│   CheckoutService    │  ← high-level
└──────────┬───────────┘
           │ depends on (abstraction)
           ↓
┌──────────────────────┐
│   OrderRepository    │  ← Protocol (abstraction)
│   (Protocol)         │
└──────────┬───────────┘
           ↑
           │ implements
┌──────────┴───────────┐
│ PostgresOrderRepo    │  ← low-level (detail)
└──────────────────────┘

Now the arrows point: both sides look at the abstraction. Neither depends on the other directly.

The dependency is "inverted". Before, the business depended on the DB. Now both depend on a contract that the business side itself defined.


Who owns the abstraction

This is critical and often missed.

high-level    ──→   ABSTRACTION   ←──   low-level
                       ↑
                  "owner" — high-level
                  (business decides what it needs)

OrderRepository.save(order) is defined by the business logic, because the business knows what it wants to save. The implementation adapts to the contract.

The low-level detail does not get to define the shape of the abstraction. Otherwise it is "high-level depends on low-level" again, just through one extra layer.

Imagine OrderRepository getting a method execute_sql(query: str). That means the abstraction now "knows about SQL". That is a leak of details into the abstraction. DIP is broken, even with a Protocol.


DIP vs DI: the difference

DIP (Dependency Inversion Principle) DI (Dependency Injection)
What is it An architectural principle A technical mechanism
Asks "Which way should the dependency arrows point?" "How do I pass a dependency into a class?"
Solved by Design and Protocols Constructor / setter / container
Can one exist without the other? DI without DIP — yes (often seen, mostly pointless) DIP without DI — theoretically, hard

In plain words: DI is a tool, DIP is the goal. If you just pass objects through the constructor but you pass concrete classes, that is DI without DIP.

# DI without DIP — anti-pattern:
class OrderService:
    def __init__(self, db: PostgresClient):    # ← concrete type
        self._db = db
# DI + DIP — right:
class OrderService:
    def __init__(self, repo: OrderRepository):  # ← abstraction
        self._repo = repo

Composition Root: where DIP meets reality

Somewhere in the program, someone has to create PostgresOrderRepository and pass it into CheckoutService. That place is called the Composition Root. It is the single point in the program that knows all the concrete classes.

Usually it is main() / app_factory() / __main__:

def main():
    # Composition Root: here and only here — concrete classes
    repo = PostgresOrderRepository(connection_string=os.environ["DB_URL"])
    payment = StripeGateway(api_key=os.environ["STRIPE_KEY"])
    notifier = SmtpEmailSender(host="smtp.gmail.com")

    service = CheckoutService(
        repository=repo,
        payment_gateway=payment,
        notifier=notifier,
    )

    # The rest of the program — knows only abstractions
    service.checkout(order)

The rest of the program does not know about Postgres, Stripe, or SMTP. That knowledge is concentrated in main().

This is "hands at the edges, brain in the middle": I/O on the edges, business in the centre.


Worked example: refactoring from spaghetti to DIP

❌ Without DIP

import psycopg2
import stripe
import smtplib

class CheckoutService:
    def __init__(self):
        self._db = psycopg2.connect("postgresql://localhost/shop")    # creates it itself
        self._stripe = stripe.api_key = "sk_test_..."                  # knows about Stripe
        self._smtp = smtplib.SMTP("smtp.gmail.com")                    # knows about SMTP

    def checkout(self, order):
        # Everything on one table
        stripe.Charge.create(amount=order.total, source=order.card_token)
        cur = self._db.cursor()
        cur.execute("INSERT INTO orders ...", (order.id, order.total))
        self._db.commit()
        self._smtp.sendmail("[email protected]", order.email, "Thanks!")

What is wrong:

✅ With DIP

# --- Abstractions (live next to the business logic) ---
class OrderRepository(Protocol):
    def save(self, order: Order) -> None: ...

class PaymentGateway(Protocol):
    def charge(self, amount: float, token: str) -> str: ...

class EmailSender(Protocol):
    def send(self, to: str, subject: str, body: str) -> None: ...

# --- Business logic (high-level) ---
class CheckoutService:
    def __init__(
        self,
        repository: OrderRepository,
        payment: PaymentGateway,
        email: EmailSender,
    ):
        self._repo = repository
        self._payment = payment
        self._email = email

    def checkout(self, order: Order) -> None:
        self._payment.charge(order.total, order.card_token)
        self._repo.save(order)
        self._email.send(order.email, "Order confirmed", f"Total: {order.total}")

# --- Implementations (low-level, in separate infrastructure/ modules) ---
class PostgresOrderRepository:
    def __init__(self, conn): self._conn = conn
    def save(self, order): ...

class StripeGateway:
    def __init__(self, api_key): self._key = api_key
    def charge(self, amount, token): ...

class SmtpEmailSender:
    def __init__(self, host): self._host = host
    def send(self, to, subject, body): ...

# --- Composition Root ---
def main():
    service = CheckoutService(
        repository=PostgresOrderRepository(connect_db()),
        payment=StripeGateway(api_key=os.environ["STRIPE"]),
        email=SmtpEmailSender(host="smtp.gmail.com"),
    )
    service.checkout(some_order)

# --- Test configuration ---
def test_checkout_calls_payment_and_repo():
    fake_repo = FakeOrderRepository()
    fake_payment = FakePaymentGateway()
    fake_email = FakeEmailSender()

    service = CheckoutService(fake_repo, fake_payment, fake_email)
    service.checkout(Order(id=1, total=100, card_token="x", email="[email protected]"))

    assert fake_payment.charged == [(100, "x")]
    assert fake_repo.saved[0].id == 1
    assert fake_email.sent[0][0] == "[email protected]"

What changed:


Hexagonal / Clean Architecture — DIP as architecture

DIP does not stop at one class. Apply it to every module of the program and you get:

        ┌─────────────────────────────────────────────┐
        │   ADAPTERS (low-level, infrastructure)      │
        │   ─────────────────────────                  │
        │   PostgresRepo, StripeGateway, SmtpSender,  │
        │   HttpController, KafkaConsumer, ...         │
        │                                              │
        │   ┌─────────────────────────────────────┐   │
        │   │       PORTS (abstractions)          │   │
        │   │       OrderRepository,              │   │
        │   │       PaymentGateway, EmailSender,  │   │
        │   │       ...                            │   │
        │   │                                      │   │
        │   │   ┌─────────────────────────────┐   │   │
        │   │   │  CORE (high-level)          │   │   │
        │   │   │  ─────────────────           │   │   │
        │   │   │  CheckoutService,           │   │   │
        │   │   │  PricingRules,              │   │   │
        │   │   │  OrderValidator             │   │   │
        │   │   └─────────────────────────────┘   │   │
        │   └─────────────────────────────────────┘   │
        └─────────────────────────────────────────────┘
                            ↑
                       dependencies
                       do not leak
                       out of the centre

This is called Ports and Adapters (Alistair Cockburn, 2005) or Hexagonal Architecture. Robert C. Martin extended the idea into Clean Architecture (2017), which is the same idea with more layers.

Big picture: SOLID is five principles, and DIP is the one that takes you straight into Clean Architecture. DIP is one common way to read the architectural conclusion of SOLID.


Anti-patterns

1. "Service Locator" instead of the constructor

class CheckoutService:
    def __init__(self):
        self._repo = ServiceLocator.get("order_repo")     # ← global
        self._payment = ServiceLocator.get("payment")

Looks like DI, but it is really a hidden global dependency. The constructor does not show what is needed, testing is hard. Anti-pattern.

2. An abstraction "too close" to the implementation

class PostgresOrderRepository(Protocol):
    def execute_sql(self, query: str) -> list: ...    # ← SQL in the Protocol!
    def begin_transaction(self) -> Transaction: ...

This is not "an abstraction over the DB", it is "an interface for Postgres, dressed up as a Protocol". The details leaked through. The business logic still knows about SQL.

A real abstraction uses domain terms: save(order), find_by_id(id). No SQL.

3. "Protocol everywhere" paranoia

class StringFormatter(Protocol):
    def to_upper(self, s: str) -> str: ...

class DefaultStringFormatter:
    def to_upper(self, s): return s.upper()

s.upper() is a standard language function. Wrapping it in a Protocol is YAGNI and pointless. DIP is about dependencies between layers, not about wrapping every call.

4. Depending on an abstraction that never changes

There are stable low-level dependencies that you should not invert: the standard library, utility functions without I/O, math.

def calculate_discount(amount, rate):
    return amount * (1 - rate)        # ← no need to invert math

DIP is about testable / replaceable infrastructure. Not about math.sqrt.

5. Abstractions with no implementation — "for the future"

class FutureCloudRepository(Protocol): ...        # planned for Q3 2026

YAGNI again. Extract Protocols for real implementations, not for imagined ones.


Relationship to other principles

Principle How DIP relates
SRP Each component under DIP has one role, which is SRP
OCP A new implementation is a new class, the business logic stays stable
LSP Implementations of a Protocol must be interchangeable, which is LSP
ISP Protocols in DIP are naturally narrow and role-shaped
Composition Inject through the constructor instead of inheriting
Testability The biggest practical consequence of DIP

DIP can be read as the architectural conclusion of SOLID. Keep the other four and you are almost doing DIP. Do DIP and the other four are almost inevitable.


Rules of thumb

  1. Business logic does not import psycopg2 / requests / boto3. If it does, that is a violation.
  2. Protocols for external services live in the business-logic module, not in infrastructure/. The abstraction belongs to the client.
  3. Composition Root is one place, ideally main() / app_factory(). The rest of the program is concrete-free.
  4. The business-logic test should not need a real Postgres. That is the DIP criterion.
  5. Protocol methods use domain terms, not tool terms. Not execute_sql, but save_order.
  6. DI ≠ DIP. DI without DIP is passing concrete classes. Check the parameter type in the constructor.
  7. YAGNI on top of DIP. Do not extract an abstraction if you have one implementation and no test mock in sight.

One-line summary

High-level does not know low-level. Both know a Protocol in the middle, defined by the business side. The Composition Root wires it all together. That is the inversion: the dependency arrows no longer point "down", they point "to the centre". Clean and Hexagonal Architecture are built on this.