#engineering #software #design #engineering-principles #solid-principles
The Dependency Inversion Principle (DIP) is a software engineering principle which dictates that the static dependencies should be inversed to the control flow. It is the D of the SOLID principles.
This means that if module A (the consumer) calls module B (the provider), then module B should have a code dependency on module A, and not the opposite. "High level modules should not depend on low-level modules"
This principle is decoupling consumers from providers, by allowing the consumers (i.e. Those with most abstracted businessman logic) to focus on the what while ignoring the how. This makes the actual implementation susbstitutable for another, therefore improving:
- testability, by allowing to substitute infrastructure implementations by mocks
- decoupling of development, for the same reason
- maintainability, by maximizing the chances that an evolution on infrastructure code won't require changes on consumer modules
- evolutivity, by allowing the replacement of one infrastructure piece by another by just rewriting adapters.
In OOP this is implemented by using an interface, which acts as a contract for the consumer.
This is sometimes criticized as adding complexity to the code uselessly. In my experience, everytime I forgone this principle (or encountered a transgression of it) ended up with more work.
delegation frameworks are a real life example of DIP: leadership injects a decision framework into the team (static dependency), which then refers to it at run time to make decisions (runtime dependency)
Clean architecture, Robert C. Martin, is re-presenting the SOLID principles that he introduced.
Wikipedia / Dependency inversion principle