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 NotImplementedErrorLow-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:
- OrderService depends on the abstraction, not on a concrete repository. This means the business logic is not tied to MySQL, Postgres, or anything else.
- Concrete implementations depend on the abstraction, not the other way around.
MySqlOrderRepositoryandPostgresOrderRepositoryimplement one contract. - Infrastructure can be changed without changing the business code. Want to switch to a different database? Just create a new implementation.
- Testing becomes simple. You can supply a mock:
python
class FakeRepo(OrderRepository):
def save(self, order):
print("Fake save")- 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.