I've been reading up on the Factory pattern, and have come across articles that suggest using the Factory pattern in conjunction with dependency injection to maximize reusability and testability. Although I have not been able to find any concrete examples of this Factory-DI hybrid, I'm going to try and give some code examples of my interpretation. However, my question is really about how this approach improves testability.
So we have a Widget
class:
public class Widget {
// blah
}
And we want to include a WidgetFactory
to control the construction of Widget
s:
public interface WidgetFactory {
public abstract static Widget getWidget();
}
public class StandardWidgetFactory implements WidgetFactory {
@Override
public final static Widget getWidget() {
// Creates normal Widgets
}
}
public class TestWidgetFactory implements WidgetFactory {
@Override
public final static Widget getWidget() {
// Creates test/mock Widgets for unit testing purposes
}
}
Although this example uses Spring DI (that's the only API I have experience with), it doesn't really matter if we're talking about Guice or any other IoC framework; the idea here is that we're now going to inject the correct WidgetFactory
implementation at runtime to depending on whether we are testing the code or running normally. In Spring the beans config might look like this:
<bean id="widget-factory" class="org.me.myproject.StandardWidgetFactory"/>
<bean id="test-widget-factory" class="org.me.myproject.TestWidgetFactory"/>
<bean id="injected-factory" ref="${valueWillBeStdOrTestDependingOnEnvProp}"/>
Then, in the code:
WidgetFactory wf = applicationContext.getBean("injected-factory");
Widget w = wf.getWidget();
This way, an environmental (deployment-level) variable, perhaps defined in a .properties file somewhere, decides whether Spring DI will inject a StandardWidgetFactory
or a TestWidgetFactory
.
Am I doing it right?!? This seems like an awful lot of infrastructure just obtain good testability for my Widget
. Not that I'm opposed to it, but it just feels like over-engineering to me.
The reason why I am asking this is because I will have other objects in other packages, which have methods that use Widget
objects inside of them. Perhaps something like:
public class Fizz {
public void doSomething() {
WidgetFactory wf = applicationContext.getBean("injected-factory");
Widget widget = wf.getWidget();
int foo = widget.calculatePremable(this.rippleFactor);
doSomethingElse(foo);
}
}
Without this huge, seemingly-over-engineered setup, there would be no way for me to inject "mock Widgets
" into my unit test for Fizz::doSomething()
.
So I'm torn: on one end it just feels like I'm overthinking things - which I may very well be doing (if my interpretation is incorrect). On the other hand I don't see any clean way to get around it.
As a segue into a tangential question, this also raises another huge concern of mine: if my interpretation is correct (or even somewhat correct), then does this mean we need Factories
for every object?!?
That sounds like way-overengineering! What's the cut-off? What's the line in the sand that demarcates when to use a Factory, and when not to?! Thanks for any help and apologies for a verbose question. It's just got my head spinning.
Dependency injection helps if you have a class that needs a dependent class-instance to do some sub-processing. Instead of DI you can seperate the logic of a business-method into a data-gethering-part (that is not unit-testable) and a calculation part that can be unit-tested.
By using dependency injection, you make creating test doubles (commonly called “mocks”) much more straightforward. If you pass dependencies to classes, it's quite simple to pass in a test double implementation. If dependencies are hard-coded, it's impossible to create test doubles for those dependencies.
Advantages. A basic benefit of dependency injection is decreased coupling between classes and their dependencies. By removing a client's knowledge of how its dependencies are implemented, programs become more reusable, testable and maintainable.
Dependency injection is a programming technique that makes a class independent of its dependencies. It achieves that by decoupling the usage of an object from its creation. This helps you to follow SOLID's dependency inversion and single responsibility principles, in order to write a good programme.
DI/IoC helps testing because you can decide, easily, what implementation to use, without modifying the code that uses it. This means you can inject a known implementation to exercise specific functionality, e.g., simulate a web service failure, guarantee good (or bad) input to a function, etc.
Factories are not required to make DI/IoC work. Whether or not a factory is required depends entirely on usage specifics.
public class Fizz {
@Inject // Guice, new JEE, etc. or
@Autowired // Spring, or
private Widget widget;
public void doSomething() {
int foo = widget.calculatePremable(this.rippleFactor);
doSomethingElse(foo);
}
}
In your Fizz example class, it's a DI anti-pattern to make an explicit call into the DI framework to get the bean you want. The whole point of DI is the Hollywood principle (don't call us, we'll call you). So your DI framework should be injecting a Widget into Fizz.
When it comes to testing, my preference is
Some people like to run tests inside their DI container, but I don't see the point in this for unit tests - it just creates an extra lot of configuration to maintain. (For integration tests it's worthwhile, but you should still have as much of your DI context as possible in common between the production and integration-test contexts.)
The conclusion of all that is that I don't see a whole lot of use to the Factory pattern.
Can you give us a link to the article(s) you've been reading? I'll see if I can dig up one or two myself.
Edit: Here's the promised link: Is Dependency Injection Replacing the Factory Patterns?, one in a series of rather good articles about DI.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With