Dependency Inversion Principle

Dependency Inversion Principle

The last principle of SOLID (DIP) was bit confusing for me

DIP: stands for Dependency Inversion Principle.

Actually what does it inverts?

It inverts the way we think about objects dependency.

DIP states that a high-level class must not depend upon a lower level class. They must both depend upon abstraction.

Here the abstraction can be an interface or abstract class. Let go for an example to illustrate the priciple.

public class BMW 
{
? ? public string Name { get; set; }
? ? public long Speed { get; set; }
? ? public long Price { get; set; }
? ? .
? ? .
? ? public BMW() {
? ? ? ? var wheel = new BMWWheel() {
	? ?     ....
	? ?     .... logic to build the wheel
	    };


? ? ? ? SetWheel(wheel);
? ? }


? ? private SetWheel(BMWWheel wheel) {
? ? ? ? ... complete the setup for wheel
? ? }
}
        

BMW is concerned with handling lot more functionality such as engine, speed, starting the car etc. See here the BMW is a higher level concept than the BMWWheel. The higher level class is dealing with the creation process of the BMWWheel.

According to DIP, these both class should depend upon abstruction not upon each others. So for solution we can introduce an interface that specifies BMW wheel specification and we are at liberty to inject any implementation of its.?

public interface IBMWWheel {
    float Radius { get; set; }
    string Color { get; set; }
? ? ...
? ? ... wheel specifications
}


public class BMWWheel : IBMWWheel {
    public float Radius { get; set; }
    public string Color { get; set; }
? ? ....
? ? .... interface implementation?
}        

Now we can inject the BMWheel by below modificatoin of the BMW class

public class BMW 
{
? ? public string Name { get; set; }
? ? public long Speed { get; set; }
? ? public long Price { get; set; }
? ? .
? ? .

? ? public BMW(IBMWWheel wheel) {
? ? ? ? SetWheel(wheel);
? ? }


? ? private SetWheel(IBMWWheel wheel) {
? ? ? ? ... complete the setup for wheel
? ? }
}        

See the beauty, we can inject any implementation of the IBMWWheel interface now.

So BMW is dealing with the IBMWWheel for the wheel setup and any wheel class will deal with the IBMWWheel interface specification.

Therefore, The BMW class is not bothered or concerned about wheel creation anymore :)

BMW --> IBMWWheel <-- Wheel        

Thanks for reading, I am expecting your suggestion.

MD ZIAUL HOQ

Fashion & Apparels | Lowest MOQ | Best Supply Chain

2 年

Good one I believe although it's far from my understanding.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了