Skip to main content

Example of DIP compliance

Correct DIP compliance is achieved when a high-level module depends not on a concrete class but on an abstraction, and the concrete implementation is supplied from outside.

Below is a correct example.


Abstraction (contract)

python
class OrderRepository: def save(self, order): raise NotImplementedError

Low-level implementations

python
class MySqlOrderRepository(OrderRepository): def save(self, order): print("Saving to MySQL") class PostgresOrderRepository(OrderRepository): def save(self, order): print("Saving to Postgres")

High-level module (does not depend on details)

python
class OrderService: def __init__(self, repo: OrderRepository): self.repo = repo # depends on the abstraction def create_order(self, order): self.repo.save(order)

Usage (dependency injection)

python
repo = MySqlOrderRepository() service = OrderService(repo) service.create_order("order-1")

If needed:

python
service = OrderService(PostgresOrderRepository())

And no changes to OrderService at all.


Why this is DIP compliance:

  1. OrderService depends on the abstraction, not on a concrete repository. This means the business logic is not tied to MySQL, Postgres, or anything else.
  2. Concrete implementations depend on the abstraction, not the other way around. MySqlOrderRepository and PostgresOrderRepository implement one contract.
  3. Infrastructure can be changed without changing the business code. Want to switch to a different database? Just create a new implementation.
  4. Testing becomes simple. You can supply a mock:
python
class FakeRepo(OrderRepository): def save(self, order): print("Fake save")
  1. The architecture becomes flexible and extensible.

Summary

In this example, DIP is honored: the high-level module (OrderService) depends only on the interface (OrderRepository), while the concrete details are implemented separately and supplied from outside.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.