Dependency Injection for Testability

My latest venture in improving my code has been incorporating the concept of Dependency Injection. In general, the overarching idea has to do with the the law of demeter. That is, the objects of my application should only collaborate or call actions on objects they use directly. For example, rather than passing a reference to a "service locator" or more commonly a shell or application class in Actionscript:
protected var loader:ILoader;
LoadedSWF(app:IApp)
{
    loader = app.getLoader();
}
I would say something like this instead:
protected var loader:ILoader;
LoadedSWF(loader:ILoader)
{
    this.loader = loader;
    ...
    (maybe queue up some thumbnails at this point)
}
The end goal is to have an object which only requires it's collaborators. There's no reason for this loaded swf to know about the app at large; suppose we want to drop it into another application context that simply isn't built within our "app framework?"

Miško Hevery recently gave a talk on this, which I've linked here at the end of the post. Some great points to note:

  • Object instantiation should be abstracted to factories to wire up your application. You can group factory logic together based on what the object lifetimes are of what they create. You might create a factory for compile time objects, runtime (usually loaded swfs) or service lifetime. With each case you only want to inject an object in the constructor that has a lifetime greater than or equal to the injectee.
  • One of the best examples given is when you're purchasing something, do you give the clerk your wallet or the cash? In the same way, you should give your objects what they need directly instead of massaging data.
Here are the tubes:

I'll be posting more on this topic later as it relates specifically to Actionscript.
blog comments powered by Disqus