August 08, 2006
Dependency Inversion Principle
[edited 08/15 - fixed typos and phrasing (thanks to Paul Gardner)]
One of the simplest, yet most fundamental, object-oriented design principles is Dependency Inversion Principle (not to be confused with Dependency Injection or Inversion Of Control).
The principle simply states that:
- Higher level modules should not depend on lower level modules. Both should depend on abstractions (interfaces or abstract classes).
- Abstractions should not depend on implementations.
The principle is simple since unlike some of the other principles it is structural and doesn't require a lot of thinking (vs. other principles like YAGNI, OCP, ISP, etc.).
The principle is fundamental as it is one of the main difference from procedural programming (if you remember what that is). In procedural programming, you had a program that depended on its modules which then depended on its functions. If a detail in a function changed, it could have severe ripple effects on all the hierarchy that depended on it. Applying DIP means that both the program and the classes depend on interfaces (and the whole interface-based programming idea). Other implications of DIP are things like layers and the afore mentioned Dependency Injection pattern.
Applying DIP helps avoid the above mentioned problems by increasing loose coupling. Abstract interfaces are usually more stable (compared with their implementation) so it is easier to update implementation without affecting the class consumers. This also helps increase testability (easier isolation) and decrease the rigidity of the design
To sum up, DIP is easy to follow and provides some very nice benefits for your OO designs.
Posted by Arnon Rotem-Gal-Oz at 05:31 AM Permalink
|