Tuesday, January 27, 2015

What is Dependency Injection & Polymorphism


" Dependency injection is the way to decouple conventional dependency relationships between objects. "



What is meant by Dependency ?

Suppose there are two classes A and B. A can not carry out works without B and A can not be reused without re using B. For this kind of scenario we said " A depends on B "

A – Dependant
B – Dependency



What Is meant by Decouple ?

A and B classes are decoupled if A can be use without B and and B can be used without A.

Lets assume creating a drawing application with Square , Triangle and Application classes. Square and Triangle class has same method name called draw() which draws square for a Square object and triangle for Triangle object.


Polymorphism to rescue !

The Greek meaning of the word "polymorphism" is "having different forms". Same object having different object behaviors ! 



Added interface called Shape and the common method draw() for both Triangle and Square. Square and Triangular classes implements Shape interface.

Shape triangular = new Triangular();
triangular.draw();                                                  
Shape square = new Square();
square.draw();



Lets Inject Dependencies !


Created a new class called DrawingTool and added a private member of Shape type (shape) and a setter for that. Created a method called drawShape(). Note that in DrawingTool class does not initiate any object. DrawingTool assumes that It will be provided a initiated object. 

Advantage !

By using this method we can separate dependency from a whole class (DrawingTool) which does not know what to draw. Lets say if we want to draw a triangle we don't have to modify the DrawingTool class. Only thing to do is pass a triangular to the setter. 

Dependency to the triangle that the DrawingTool class has injected by the Application class. This is the way of injecting dependency.

No comments:

Post a Comment