Posts Tagged ‘injectorjs’


Dependency Injection And IoC Containers

05.10.2013

The dependency injection pattern is one of my all-time favorite patterns in software design. The concept, in its most simple form, is so simple yet so powerful.

In essence, it takes us from this:

var TweetStream = function() {
    this.twitter = new TwitterService();
};
 
TweetStream.prototype.streamTweets = function() {var tweets = this.twitter.getTweets();};
 
var stream = new TweetStream();
stream.streamTweets();

To this:

var TweetStream = function(twitter) {
    this.twitter = twitter;
};
 
TweetStream.prototype.streamTweets = function() {var tweets = this.twitter.getTweets();};
 
var twitter = new TwitterService();
var stream = new TweetStream(twitter);
stream.streamTweets();

So what’s the big deal?

In the first example, TweetStream creates the TwitterService instance. TweetStream is forced to have a knowledge of (1) the exact “class” it should use to communicate with Twitter, (2) where and how to access the constructor, and (3) how to create an instance and appropriately initialize the object (passing parameters to the constructor, calling methods after the fact, etc.).

In the second example, TweetStream does not need to know any of these things since TwitterService is created by a third party and later passed into TweetStream. TweetStream only needs to know how to interact with the instance it is passed.

Although seemingly benign, the additional knowledge that TweetStream is forced to have in the first example increases its coupling to its dependencies while decreasing its own cohesion. The additional coupling leads to code that can be difficult to test and less flexible at runtime. If we were to “inject” the dependencies rather than forcing TweetStream to create or find them, we can easily mock dependencies during unit tests and provide them directly to the subject being tested. At runtime, we can easily swap out the object being provided as a dependency based on rules or contexts. Continue reading »