What Does ‘Abstractions Should Not Depend on Details’ Mean?

designsolid

Most readers will be familiar with Bob Martin's famous dependency inversion principle, which states

  1. High-level modules should not depend on low-level modules. Both should depend on abstractions

  2. Abstractions should not depend upon details. Details should depend upon abstractions

I believe I understand it all pretty well, except for the first sentence in the second line – "Abstractions should not depend upon details". What does this mean exactly? What would be a simple example of an abstraction being dependent upon a detail?

Best Answer

What he's saying here is that you should avoid a scenario where a base class takes a dependency to meet the need of a descendant. Let's look at the case of a Switch and its descendant the TimedSwitch. The TimedSwitch is a Switch that resets itself after a certain amount of time. We have the TimedObject class already so it would make sense for TimedSwitch to derive from it...however TimedSwitch already derives from Switch. So in order to meet the needs of the TimedSwitch, Switch will inherit from TimedObject even though it doesn't need that functionality itself.

The Switch (abstraction) is dependent on the details of TimedSwitch. To fix this violation of the DIP, we have TimedSwitch implement ITimedObject and delegate to a contained TimedObject class (prefer composition over inheritance).

Another more generic example is the layered approach. The higher level layers are abstractions and in most cases they depend on the details. DIP says that instead, the lower layers should conform to an interface which they both take dependency on. Thus the dependency is inverted from Higher Layer depending on lower layer to both layers depending on an interface.

Related Topic