202204291515 Dependency inversion
The dependency inversion principle of the 202204272244 SOLID design principles for software development, which states:
Depend upon abstractions, not concretions.1
In slightly stricter form:
- High-level modules should not import anything from low-level modules. Both should depend on abstractions (e.g., interfaces).
- Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.
The idea behind this is that interactions between modules should be thought of as abstract concepts. Thinking about the interaction itself as a concept should reduce coupling between the modules, instead preferring the modules to couple themselves to the interaction. This should also allow the interaction to be lighter and simpler since we don't allow for implementation details to creep in on accident.
In practice, this means that functions and objects should use interfaces, traits, or types instead of concrete objects or functions. One simple and obvious example is substituting the implementation of an interface with a test version for testing.
There are times and types of projects where this may not be necessary. For instance, doing one specific concrete implementation is typically better in a game whose design and mechanics are relatively finalized. You can get more performance and the code won't be used over time to do drastically different tasks.
On the other side of the coin is something like a web server for an application. The odds of needing drastically new features and implementations of things over time is much higher, so we choose to accept the complexity of the abstractions in favor of the flexibility it gives us.
-
Wikipedia contributors. (2022). SOLID. In Wikipedia. https://en.wikipedia.org/w/index.php?title=SOLID&oldid=1069309351 ↩