Search code examples
oopinversion-of-controlsolid-principlesdesign-principlesdependency-inversion

What is mean by "Abstractions should not depend on details. Details should depend on abstractions" in Dependency inversion principle[DIP] means?


Before asking this question I like to say that this question in stackoverflow is very similar to my question but still the concept is not clear very confusing.

I am trying to understand the dependency inversion principle but I could not able to understand it completely?

The below are two point which DIP says

A. High-level modules should not depend on low-level modules. Both should depend on abstractions. B. Abstractions should not depend on details. Details should depend on abstractions.

I can able to grasp the first point but I cannot able to get the second point, its look like both are same. After lots of search in stackoverflow & other sites I can able to understand both are trying to say different thing but I could not able to get it.

Let’s consider an example:

Let’s consider SalaryCalculator class [High level module] which is used to calculate the salary of employee. Which uses BonusCalculator [High level module] to calculate the salary as shown below. Since SalaryCalculator is using BonusCalculator it’s violating the first point of “High-level modules should not depend on low-level modules. Both should depend on abstractions”.

enter image description here

So we introduced abstraction between both as shown below:

enter image description here

Here details [Low & High level Modules] is dependent on Abstraction & abstraction is not dependent on details. So in DIP what that second point is trying to tell? If both are same why it is made as two points?

If some one gives me an code example , that will be very useful.


Solution

  • Let's break that part B down further.

    Abstractions should not depend on details. This can mean that your interface declaration (your abstraction) should avoid including concrete types. Think of the difference between distance(int X1, int Y1, int X2, int Y2) and distance(Point A, Point B). What if you have coordinates measured in floating point, or lat/lon, or polar coordinate systems? What if you change to a 3D space? You'll have to reimplement every routine that uses your distance function.

    Details should depend on abstractions. As far as is practical, continue to use an abstraction layer to avoid dependencies on concrete types.

    It's all about minimizing the impact of change. The less your code depends on other things, the more it enables that other code to change.