Saturday, July 26, 2014

IOC - Newables & Injectables and the Abstract Factory

In my reading around the blogs and StackOverflow posts this week I came across the topic of newables and injectables in Ioc.  If your not familiar with the topic the following two posts explain in detail the issue of these two types of objects in our code.

To new or not to new
How to write testable code

To summarize, newables should only ask for other newables, and injectables should only ask for other injectables in their constructors.  Newables can be aware of injectables (pass them through methods), but should not take instances of injectables in the constructor.  If these rules are followed, life will be good, your system will be loosely coupled and you'll be in a state of testing nirvana.

The reality is that very often you'll have a condition in the code that is unknown until run time. Say you have a class that coordinates some sort of work, and you end up with something like this.
public class WorkDoer : IWorkDoer
   public WorkDoer(taskRunner ITaskRunner, workToBeDone WorkObject){}

In the above example, the rule of injectables and newables has been broken, and yes it does complicate things, but not horribly.  Now to deal with this in your code, an Abstract Factory will be needed to create a WorkDoer instance.  The Abstract Factory is great because it allows us to keep our code testable and loosely coupled.  In the test harness, if your using a mocking framework you can simply have your abstract factory return a mock of whatever the factory creates.
Following the newable and injectable rule certainly makes life easier.  It keeps each part of the code relatively simple to test in isolation from other parts of code.  However, in the case where an injectable must have an instance of a newable passed through the constructor, the Abstract Factory pattern will save the day. 

Mark Seemann, author of Dependency Injection in .Net, has this post on SO which is an answer to a the issue discussed above.  I point this out as Mark's SO answers have helped clarify many of my questions around IOC.

No comments:

Post a Comment