Sunday, December 11, 2016

DIP - Dependency Inversion Principle - Example

In previous post we covered what is DIP. Here I am going to show one more example of DIP.

Lets see a real- time example, we all know that whenever a bill is printed, an invoice is required to be generated and whenever an invoice is generated a bill must be printed. Lets assume that we have two classes Bill and Invoice as below.


When the below code is executed, we get the stack overflow error.

Now how do we solve this issue? This is where DIP comes into the picture, where we inject the dependencies to the dependent object. See the below code how the dependencies are injected to resolve stack overflow issues.



What we saw in above example is to achieve DIP using Constructor injection. 

PS: DIP is just the principle which requires that all your code's entities to depend only on the details they really need. DI is a process of passing the "abstract details" to the entity that really needs these derails. 

No comments:

Post a Comment