Thursday, March 20, 2014

Dependency Injection: Newbie’s Guide

In different branches of Engineering, Engineers design their intended devices from off-the-shelf components. They glue together components (resistors, transistors, electromagnets, etc.) through well defined interfaces (buses in case of computers) to build devices.

This is not the case in Software Engineering. Glueing software components together to build large Softwares have proven an illusive goal.

Nevertheless, Software Developers are always looking forward to reuse components or code - whether written by themselves or by others.

The problem - in the Software Development world, change is the norm.

So, how do you write Software that is flexible and maintainable?

Lets find out what the problem is. 

Suppose component B has a method b().
A calls B.b().
When we write Z, we call B.b().

But if B is replaced with G.
A can’t call B.b() anymore.
A’s B.b() has to be replaced with G.g() or equivalent.

So, in our current scheme, if we want to replace B with G,
not only do we replace B but we have to replace component A with another component X.

In general, if our code (in this case, component A) is dependent on other code (component B, C, D), then if the dependencies (any of B, C, and D) change, we have to change the dependent code (component A) as well.

Is there a way so that we can replace dependencies (B or C or D) without replacing dependents (A)?

Yes! Dependency Injection to the rescue!

Dependency Injection Frameworks enable us to inject dependencies to the dependents.

So if any of the dependencies change, we inform it to our Dependency Injection framework and the DI framework does the job of injecting the new component to dependents.

Each Dependency Injection framework has its own way of accomplishing the task.

For example, in game playing, we can write MiniMax Algorithm that returns us the next move by computer. The Algorithm is dependent on the game. We can inject any game (Dependency) we want, be it tic-tac-toe, chess, whatever.

Dependency Injection Frameworks

No comments:

Post a Comment