Skip to content

Instantly share code, notes, and snippets.

@LoganBarnett
Last active September 5, 2015 06:29
Show Gist options
  • Save LoganBarnett/7007f349573f7ebe11a7 to your computer and use it in GitHub Desktop.
Save LoganBarnett/7007f349573f7ebe11a7 to your computer and use it in GitHub Desktop.
Example of DI, and not DI.
// how it was done before we saw the light
var hats = ['cone', 'horse'];
var buzzers = ['foo', 'bar', 'bazz'];
var drinkFn = function() {
drunkify();
}
var partyObj = {};
partyObj.throw = function() {
// reach outside of our local scope to get what we need. Ick!
var hats = getHats();
var buzzers = getBuzzers();
var drinkFn = getDrinkFn();
// do things with this.hats, this.buzzers, and this.drinkFn
};
// screw that noise. DI to the rescue
var partyObj = {};
partyObj.throw = function(hats, buzzers, drinkFn) {
// now do things with hats, buzzers, and drinkFn
}
// Now to test it!
var partyObj = require('di');
// what do I do if in my test I don't want to get drunk? Hey it could happen. I can stop whenever I want!
// but not this way...
// I would have to find a way to override getDrinkFn, which might be very hard depending on how buried it is.
// it's also not obvious what throw() needs or does here.
// It might be really important to change how any of the get*s work.
// Some of that data might come from disk or some remote location.
partyObj.throw();
// DI version
// MAYBE I DON'T WANT TO GET DRUNK WHILE TESTING
var drinkFn = function() {}; // deliberately not drinking
// changing things out is actually what's realy important about this.
var hats = ['cone', 'horse'];
var buzzers = ['foo', 'bar', 'bazz'];
// throw() is not in the business of knowing where to get its data from, just how to use the data.
partyObj.throw(hats, buzzers, drinkFn);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment