by Miško Hevery
Dependency injection asks us to separate the new operators from the application logic. This separation forces your code to have factories which are responsible for wiring your application together. However, better than writing factories, we want to use automatic dependency injection such as GUICE to do the wiring for us. But can DI really save us from all of the new operators?
Lets look at two extremes. Say you have a class MusicPlayer which needs to get a hold of AudioDevice. Here we want to use DI and ask for the AudioDevice in the constructor of the MusicPlayer. This will allow us to inject a test friendly AudioDevice which we can use to assert that correct sound is coming out of our MusicPlayer. If we were to use the new operator to instantiate the BuiltInSpeakerAudioDevice we would have hard time testing. So lets call objects such as AudioDevice or MusicPlayer "Injectables." Injectables are objects which you will ask for in the constructors and expect the DI framework to supply.
Now, lets look at the other extreme. Suppose you have primitive "int" but you want to auto-box it into an "Integer" the simplest thing is to call new Integer(5) and we are done. But if DI is the new "new" why are we calling the new in-line? Will this hurt our testing? Turns out that DI frameworks can't really give you the Integer you are looking for since it does not know which Integer you are referring to. This is a bit of a toy example so lets look at something more complex.
Lets say the user entered the email address into the log-in box and you need to call new Email("a@b.com"). Is that OK, or should we ask for the Email in our constructor. Again, the DI framework has no way of supplying you with the Email since it first needs to get a hold of a String where the email is. And there are a lot of Strings to chose from. As you can see there are a lot of objects out there which DI framework will never be able to supply. Lets call these "Newables" since you will be forced to call new on them manually.
First, lets lay down some ground rules. An Injectable class can ask for other Injectables in its constructor. (Sometimes I refer to Injectables as Service Objects, but that term is overloaded.) Injectables tend to have interfaces since chances are we may have to replace them with an implementation friendly to testing. However, Injectable can never ask for a non-Injectable (Newable) in its constructor. This is because DI framework does not know how to produce a Newable. Here are some examples of classes I would expect to get from my DI framework: CreditCardProcessor, MusicPlayer, MailSender, OfflineQueue. Similarly Newables can ask for other Newables in their constructor, but not for Injectables (Sometimes I refer to Newables as Value Object, but again, the term is overloaded). Some examples of Newables are: Email, MailMessage, User, CreditCard, Song. If you keep this distinctions your code will be easy to test and work with. If you break this rule your code will be hard to test.
Lets look at an example of a MusicPlayer and a Song
class Song { Song(String name, byte[] content);}class MusicPlayer { @Injectable MusicPlayer(AudioDevice device); play(Song song);}
Notice that Song only asks for objects which are Newables. This makes it very easy to construct a Song in a test. Music player is fully Injectable, and so is its argument the AudioDevice, therefore, it can be gotten from DI framework.
Now lets see what happens if the MusicPlayer breaks the rule and asks for Newable in its constructor.
class Song { String name; byte[] content; Song(String name, byte[] content);}class MusicPlayer { AudioDevice device; Song song; @Injectable MusicPlayer(AudioDevice device, Song song); play();}
Here the Song is still Newable and it is easy to construct in your test or in your code. The MusicPlayer is the problem. If you ask DI framework for MusicPlayer it will fail, since the DI framework will not know which Song you are referring to. Most people new to DI frameworks rarely make this mistake since it is so easy to see: your code will not run.
Now lets see what happens if the Song breaks the rule and ask for Injectable in its constructor.
class MusicPlayer { AudioDevice device; @Injectable MusicPlayer(AudioDevice device);}class Song { String name; byte[] content; MusicPlayer palyer; Song(String name, byte[] content, MusicPlayer player); play();}class SongReader { MusicPlayer player @Injectable SongReader(MusicPlayer player) { this.player = player; } Song read(File file) { return new Song(file.getName(), readBytes(file), player); }}
At first the world looks OK. But think about how the Songs will get created. Presumably the songs are stored on a disk and so we will need a SongReader. The SongReader will have to ask for MusicPlayer so that when it calls the new on a Song it can satisfy the dependencies of Song on MusicPlayer. See anything wrong here? Why in the world does SongReader need to know about the MusicPlayer. This is a violation of Law of Demeter. The SongReader does not need to know about MusicPlayer. You can tell since SongReader does not call any method on the MusicPlayer. It only knows about the MusicPlayer because the Song has violated the Newable/Injectable separation. The SongReader pays the price for a mistake in Song. Since the place where the mistake is made and where the pain is felt are not the same this mistake is very subtle and hard to diagnose. It also means that a lot of people make this mistake.
Now from the testing point of view this is a real pain. Suppose you have a SongWriter and you want to verify that it correctly serializes the Song to disk. Why do you have to create a MockMusicPlayer so that you can pass it into a Song so that you can pass it into the SongWritter. Why is MusicPlayer in the picture? Lets look at it from a different angle. Song is something you may want to serialize, and simplest way to do that is to use Java serialization. This will serialize not only the Song but also the MusicPlayer and the AudioDevice. Neither MusicPlayer nor the AudioDevice need to be serialized. As you can see a subtle change makes a whole lot of difference in the easy of testability.
As you can see the code is easiest to work with if we keep these two kinds objects distinct. If you mix them your code will be hard to test. Newables are objects which are at the end of your application object graph. Newables may depend on other Newables as in CreditCard may depend on Address which may depend on a City but these things are leafs of the application graph. Since they are leafs, and they don't talk to any external services (external services are Injectables) there is no need to mock them. Nothing behaves more like a String like than a String. Why would I mock User if I can just new User, Why mock any of these: Email, MailMessage, User, CreditCard, Song? Just call new and be done with it.
Now here is something very subtle. It is OK for Newable to know about Injectable. What is not OK is for the Newable to have a field reference to Injectable. In other words it is OK for Song to know about MusicPlayer. For example it is OK for an Injectable MusicPlayer to be passed in through the stack to a Newable Song. This is because the stack passing is independent of DI framework. As in this example:
class Song { Song(String name, byte[] content); boolean isPlayable(MusicPlayer player);}
The problem becomes when the Song has a field reference to MusicPlayer. Field references are set through the constructor which will force a Law of Demeter violation for the caller and we will have hard time to test.
function showProgress(status) { status.message = "Loading"; for (var time = 1000; time <= 3000; time+= 1000) { // Append a '.' to the message every second for 3 secs. setTimeout(function() { status.message += "."; }, time); } setTimeout(function() { // Special case for the 4th second. status.message = "Done"; }, 4000);}
function testUpdatesStatusMessageOverFourSeconds() { Clock.reset(); // Clear any existing timeout functions on the event queue. var status = {}; showProgress(status); // Call our function. assertEquals("Loading", status.message); Clock.tick(2000); // Call any functions on the event queue that have been // scheduled for the first two seconds. assertEquals("Loading..", status.message); Clock.tick(2000); // Same thing again, for the next two seconds. assertEquals("Done", status.message);}
We talked about how it is important to separate the new operators from the application logic. This separation forces your code to have factories which are responsible for wiring your application together. By separating these responsibilities the tests can always wire together a subset of an application with key components replaced for friendlies making testing easier and more focused.
Let's look at a sample factory
class CarFactory {Car create() { return new Car( new EngineCompartment( new Engine(), new Door(new PowerWindow()), new Door(new PowerWindow()), new PowerSeat(), new PowerSeat() new ManualTransmission(), new PowerSteering(), new Battery() ), new Cabin( new Door(new PowerWindow()), new Door(new PowerWindow()), new PowerSeat(), new PowerSeat() ), Arrays.asList( new Wheel(new Tire(), new Rim()), new Wheel(new Tire(), new Rim()), new Wheel(new Tire(), new Rim()), new Wheel(new Tire(), new Rim()) ) );}}
new Door(new PowerWindow()), new Door(new PowerWindow()), new PowerSeat(), new PowerSeat()
Car(EngineCompartment ec, Cabin c, List ws);EngineCompartment(Engine e, Transmission t, Steering s, Battery b);Cabin(Door driverDoor, Door passengerDoor, Seat driverSeat, Seat passengerSeat);Engine(float dissplacement, int pistonCount);Battery(float voltage);Door(Window window); new Door(new PowerWindow()), new Door(new PowerWindow()), new PowerSeat(), new PowerSeat()PowerWindow() implements Window;PowerSeat() implements Seat;Wheel(Tire tire, Rim rim);...
Imagine you could just ask for things. Lets start simple and look at the Wheel. The constructor of Wheel needs a Tire and Rim. So when we ask for a Wheel it should be obvious that we want new Wheel(new Tire(), new Rim()). Why do we need to make this explicit in our factory? Lets build a framework from which we can ask for a class and it returns an instance of that class. So in our case if we ask for getInstance(Wheel.class) it returns a new Wheel(new Tire(), new Rim()). Now a framework like this is easy to build since all we need to do is look at the constructor and recursively try to instantiate the objects until all recursive constructors are satisfied.
But things are a bit more complicated than that. What if we ask for Cabin, as in getInstance(Cabin.class)? Well Cabin needs two Doors and two Seats, but Seat is an interface so we have to make a decision: What subclass of Seat should we instantiate? To help our framework make that decision, somewhere we will add a bind method such as bind(Seat.class, PowerSeat.class). Great! Now when we call getInstance(Seat.class) the framework returns new PowerSeat(). Similarly, we will have to call bind(Window.class, PowerWindow.class). Now we can call getInstance(Cabin.class) and the framework will return new Cabin(new Door(new PowerWindow()), new Door(new PowerWindow()), new PowerSeat(), new PowerSeat()).
Notice that closer a class you ask for is to the root (Car in this case), the more work will the framework do for us. So ideally we just want to ask for the root object, Car. Calling getInstance(Car.class) will cause the framework to do all of the work originally in our factory.
As you can see a framework which will call the new operators on your behalf is very useful. This is because you only have to ask for the root object (in our case the Car) and the framework will build the whole object graph on your behalf. This kinds of frameworks are called Automatic Dependency Injection frameworks and there are few of them our there. Namely GUICE, PicoContainer, and Spring.
Since I know most about GUICE, The above example can be rewritten in GUICE like this:
class CarModule extends AbstractModule() {public void bind() { bind(Seat.class, PowerSeat.class); bind(Seat.class, PowerSeat.class); bind(Transmission.class, ManualTransmission.class); // maybe use a provider method?(jwolter) // maybe explain the need for different wheels, so use a Provider; bind(new TypeLiteral>(){}) .toProvider(new Provider>(){ @Inject Provider wp; List get() { return Array.asList(wp.get(), wp.get(), wp.get(), wp.get()); } });}// or, what I think is simpler and clearer@ProvidesList provideWheels(Provider wp) { return Array.asList(wp.get(), wp.get() wp.get(), wp.get());}}// Then somewhere create your application, using the injector only// once, for the root object.Injector injector = Guice.createInjector(new CarModule());Car car = injector.getInstance(Car.class);
GIMME lol_io LIKE LOLIOSO IM LIKE PROCESSIN WIT DATAZ OK? GIMME EACH BUCKET IN UR DATAZ OK? BUCKET OWN FUBARRED? N CAN HAS NONE NOPE? N CAN HAS 1 KTHXBYE NIZ __name__ KINDA LIKE “__main__”? UR PROCESSIN WIT LOLIO OWN GET_SOME_DATAZ BTW, GET_SOME_DATAZ USES UR INTERNETS LOL
GIMME mock_lol_io LIKE LOLIO BTW, GIMME THING TO TESTBTW, TEST THE THING NOW KTHX
BTW, SOMETIMES THEY BE CALLIN DIS DEPENDENCY INJECTION ROFLBTW, YOU CAN UZE MOCKZ N STUF FER DIS LOOK:IN MAI library GIMME mock_filesystem LIKE LOL_FAKE_FILEYSTEMBTW, NOW U CAN USE LOL_FAKE_FILESYSTEM TO MAKE FAKE FILEZ IN MEMORY N STUFFBTW, IS FASTER THAN OPENIN FILEZ ON TEST SERVAR