Skip to main content

Example of a DIP violation

A DIP violation occurs when a high-level module directly depends on a concrete implementation of a low-level module. This makes the system rigid, hard to test, and hard to change.

Here is a typical example of the violation:


Example of a DIP violation

python
class MySqlOrderRepository: def save(self, order): print("Saving order to MySQL") class OrderService: def __init__(self): self.repo = MySqlOrderRepository() # DIP violation def create_order(self, order): self.repo.save(order)

Why this is a DIP violation:

  1. A high-level module depends on a low-level one OrderService: business logic. MySqlOrderRepository: infrastructure. The business logic knows about technical details, which violates DIP.
  2. The implementation cannot be replaced without rewriting OrderService Want to switch to Postgres? You have to change the constructor:
python
self.repo = PostgresRepository()

This breaks the open/closed principle and makes the code fragile. 3. OrderService is hard to test You cannot supply a fake repository or a mock: it is hardwired in. Tests are impossible without a real database. 4. Business code depends on details that change often The repository, drivers, and connection library change. Business logic should be stable. The direct coupling breaks the architecture.


Summary

OrderService should depend on an abstraction, not on a concrete class. In this example, the business logic is hardwired to MySQL: this is a direct violation of the Dependency Inversion Principle.

Short Answer

Interview ready
Premium

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