Codacoda
Back to Academy

coding principles

Dependency Inversion Principle

The Dependency Inversion Principle (DIP) states that high-level modules should not depend on low-level modules — both should depend on abstractions. Furthermore, abstractions should not depend on details; details should depend on abstractions. By programming to interfaces rather than concrete implementations, you decouple modules, making them independently testable and allowing implementations to be swapped without modifying consuming code.

Use Cases

  • Injecting a database adapter so business logic does not depend on a specific database driver
  • Swapping between real HTTP clients and mock clients in tests
  • Plugin systems where the core depends on a plugin interface, not specific plugins
  • Configuring logging backends (console, file, cloud) without changing application code

Visualization

BEFOREOrderServiceplaceOrder()MySQLDatabasequery()SmtpMailersend()
Speed:1x
OrderService directly instantiates MySQLDatabase and SmtpMailer. High-level policy depends on low-level implementation details.Step 1 / 7

Implementation

Output

Click "Run Code" to see output...