Dependency Inversion Principle (DIP)

Dependency Inversion Principle (DIP)

Dependency Inversion Principle (DIP)

DIP states that high level modules/classes should not depend on low level modules/classes designing. The Dependency Inversion Principle (DIP) focuses on decoupling high-level modules from low-level modules by introducing an abstraction layer, with the use of interfaces or abstract classes and reducing direct dependencies between classes.

Confused???

Let’s take an example, you went to lunch in a restaurant daily and eat chicken every day. Now think about the situation, you went to a restaurant and ordered chicken, a waiter came to you and informed you that the cook is not available today and your order won’t be served today. ?OR you are very specific about cooking, like you would like to serve your order made by a specific cook only who is not available today. The process is tightly coupled with a cook which makes it complicated.

Instead, you should only care about the order irrespective of who cooked it, if usual cook is not available today, some other cook will make it. You should not be specific about cooking, which makes your life easy.

In same way, high level class/module shouldn’t tightly to lower class implementation.

Let’s understand by example

We need to make a Employee DAL for data base operation, let consider we made EmployeeDAL for all data base operations for Employee and DAL Factory is returning EmplyeeDAL

?

We have DAL factory which return EmployeeDAL

?

And we have employee BAL

?

Now, if you look closely, EmployeeBAL has a variable employeeDAL which is assigned in constructor of EmployeeBAL

This is tight coupling and EmployeeBAL which is high level class is fully dependent on low level class and it doesn’t follow DIP principle.

?

To make it follow DIP principle, we need to make an interface and EmployeeBAL should not tightly coupled with EmployeeDAL instead it should loosely couple using interface.

?

?

Now, EmployeeDAL should implement IEmployeeDAL

?

And DAL factory should return IEmployeeDAL interface

?

?

?

Now, we can see that EmployeeBAL is no longer tightly coupled with EmployeeDAL, rather it is loosely coupled with IEmployeeDAL interface.

?

Benefits

By applying the DIP, we achieve a more flexible and modular design, enabling us to evolve and adapt our systems more easily over time.

?

?

?

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

社区洞察

其他会员也浏览了