Factory pattern using dependency injection - java

I find myself doing the following fairly regularly:
#Component
class FactoryOne {
public Object getNewMyThing() {
return new Object();
}
}
#Component
class FactoryTwo {
#Autowired
FactoryOne factoryOne;
public Object getNewMyThingTwo() {
Object one = factoryOne.getNewMyThing();
return new MyThingTwo(one);
}
}
FactoryOne does actually depend on JIT values to produce its object instance, although the example doesn't show this.
FactoryTwo is dependent on some JIT thing that factory one produces, however, whenever I write this code, I look at it and think "I must be able to let the DI framework handle this for me".
...is there a code pattern I can use to handle this?
(Example is in Spring, but happy for an answer in any DI framework)

Related

Dependency injection with #Inject

I find it odd that that I can't find this information, so please direct me to a creditable source if possible. This questions pertains only to Java.
In short, I want to know how dependency injections actually happens syntactically.
My understanding of dependency injection is the following:
public class Car {
private Engine engine
#Inject
public Car(Engine engine) {
this.engine = engine
}
}
Is the equivalent of
public class Car {
private Engine engine
public Car(Engine engine) {
this.engine = engine
}
}
Where the keyword #Inject is syntactic sugar to let Java know that the dependency engine is to be injected. This way Car won't be responsible for creating engine and therefore have a hard dependency of Engine. However, no examples have shown me how to inject it. In short:
public MyClass {
public static void main(String[] args) {
ToyotaEngine toyotaEngine = new ToyotaEngine();
HondaEngine hondaEngine = new HondaEngine();
// ??? which one to inject?
Car myCar = new Car(); // syntax?
}
}
How do I actually trigger the injection? Simply call new Car() and Engine will be pass to the constructor for me? How does Java know which Engine to inject?
Everything I've googled pertains to how to use the #Inject annotation on the class but nothing about how to actually trigger it. This article describes a configuration that looks specific to Spring and doesn't explain much. And I'm not sure what Spring is.
There is no "syntax" about it, and #Inject is not syntactic sugar. An annotation is a piece of metadata that gets recorded on an element (class, method, field, etc.), and then other software has a chance to inspect it. In the case of #Inject, some framework that you're using (Spring, CDI, Guice) looks for the annotation and, if present, executes some code that looks up and provides you with the dependency. (This is typically called a container because it contains a bunch of objects that can be looked up and injected for you. Among other things, Spring provides a DI container.)
The constructor (or setter) works entirely normally, and you can't just use new Car(). Instead, the framework, which has found an Engine somewhere, invokes new Car(engine) for you, passing in that object. If you're simply using new, then you have to provide your own values; this is very useful for tests, where you can pass in mocks or test data.
(This, by the way, is the reason that using constructor injection is nearly always the best choice; it prevents you from using new Car() when there are hidden dependencies, which wouldn't be initialized properly.)
Maybe this article (https://www.objc.io/issues/11-android/dependency-injection-in-java/) can explain, how the concept DI works in general.
In order to use DI, you need to pick a DI framework. Each framework then provides a mechanism to do and trigger DI. Spring is a framework that uses DI, but it's also more than DI and designed to deal with Server-Client-based WebApps and Rest-Services, which makes it hard to single out the sole DI aspects.

Class with different method and object design pattern

I am new with design pattern, and I don't know which I have to apply in this case.
I have some data in a file, so I have to model that data and then start a class with that data.
For the reading of the file and the modeling I choose to apply the Dao pattern, so there is interface (Interface) and his implementation (InterfaceImplementation) that read the file and return the model data (DataModel).
After I have to instantiate another class (Runner) with that model data e call one of its method.
This is what I have done:
public class Factory {
public void start() {
Interface dao = new InterfaceImplementation();
DataModel data = dao.getDataModel();
Runner runner = new Runner(data);
runner.run();
}
}
So the client call only the method new Factory().start().
I have some doubts about this solution, I don't think this is a good solution and a good applying of the Factory pattern.
I hope to have been clean, cheers.
Your Factory class is actually not an implementation of the Factory creational pattern. It is an implementation of the Facade pattern.
Your Factory class's purpose is not only to simplify the instantiation process of a Runner, but to simplify the entire process of starting a Runner which makes it more than a factory.
On a side note, naming things is one of the most important aspect in programming. Choose meaningful names of the Ubiquitous Language of your domain.
public class Factory {
public void start() {
Interface dao = new InterfaceImplementation();
DataModel data = dao.getDataModel();
Runner runner = new Runner(data);
runner.run();
}
}
2 remarks :
A factory creates an object and generally provides a instance of that. Which looks like more to a factory in your code is :
DataModel data = dao.getDataModel();
Why re-instantiate InterfaceImplementation at each start() call ?
If you have multiple DataModels, a useful factory could by example create/retrieve a specific DataModel for clients.
public class DataModelFactory {
private Interface dao = new InterfaceImplementation();
public DataModel GetDataModelXXX() {
DataModel dataModel = dao.getDataModelXXX();
return dataModel ;
}
public DataModel GetDataModelYYY() {
DataModel dataModel = dao.getDataModelYYY();
return dataModel ;
}
}
A factory is intented to ease the creation of an object. In a factory after the creation the object will be returned.
So create the Runner and give it back to the caller.
There you can decide next what to do with it.
Its also important to give the method meaningful names.
The thing that caught my attention: in your current implementation, your client is "kinda" completely decoupled from all other activities. But not in a positive way.
Your client code calls start(); and then internally, a lot of things happen. But there is not even a return value from that method.
I am wondering now: how would any of this have an "lasting" effect on your system? Are there some implicit side effects; like that Runner updating some global state singleton somewhere?
In other words: given your code, what would happen if start() is called multiple times?! Or ... zero times?!
In that sense, it is not at all clear to me how this code "relates" to anything else. And well, that looks like a problem to me that you should look into.
( and yes, I understand that my input is more of a "code/design review" than a real answer; but heck, maybe it can be helpful )

Java Object creation pattern and design

I have recently started working on a Java project that is already with a sizeable codebase developed by a team over 3 months. I noticed that at many places , some objects they are instantiating directly in the constructor of the client object , rather than using a dependency injection. I wanted to refactor the object construction into a factory and use some injection framework.
I have created a factory that essentially is a one liner for a doing new <type(some params here)>. There is nothing fancy here - no singleton , no static factory pattern. Just a newInstance() method that returns a new instance of the dependency.
To show something in code :
class A { A() {
B bobj = new B(); // A and B are coupled directly
}
}
I want to refactor this to :
BFactory {
newInstance() { return new B(); // return B implementation }
}
class A {
A(BFactory factory){
B bobj = factory.newInstance(); // A does not know about B impl
}
}
My argument is that objects should not be created anywhere in the code except in a Factory meant for that purpose. This promotes loose coupling , otherwise you are coupling the two types tightly. One senior member ( the author of the code I am trying to refactor ) feels that the one liner factory is a over-complicating design.
Are there authoritative advices/references on patterns governing this problem ? Something that can be used to decide which approach is better and why exactly ?
One senior member ( the author of the code I am trying to refactor ) feels that the one liner factory is a over-complicating design.
This looks like the crux of your question and not whether you should be refactoring the code or not so let us answer it rather than deviating from the actual question. If we consider the examples that you present in your code, I agree with your colleague. You shouldn't be creating a factory class for each dependency you want to inject. There is nothing wrong with what you are trying to achieve but the way you try to achieve it is an overkill.
You either depend upon a hierarchy of Factory classes that know how to create each and every dependency or you depend on the actual class itself and have a Container that can wire the objects together for you.
Option 1 : Depend on a common Factory
class A {
B bobj;
C cobj;
A(Factory factory){
bobj = factory.createB();
cobj = factory.createC();
}
}
Option 2 : Depend on the dependency directly
class A {
B bobj;
C cobj;
A(A a,B b) {
this.bobj = b;
this.cobj = c
}
}
You can then create a Container class that knows how to wire objects together :
class Container {
public static B createB() {
return new BImpl();
}
public static C createC() {
return new CImpl();
}
public static A createA() {
return newAImpl(createB(),createC());
}
}
The examples presented above are way too basic. In the real world, you will mostly have a more complex graph of dependencies. That's where DI frameworks come in handy instead of reinventing the wheel. If your ultimate goal is to start using a DI framework, you could go with option 2 since DI frameworks achieve inversion of control by supplying dependencies to their clients rather than the client code asking for them.
Your underlying point is perfectly valid, it's usually not a good idea to instantiate objects directly in the constructor (they may be valid exceptions from that rule).
If you do this:
class Car {
private Engine engine;
public Car() {
engine = new Engine();
}
}
You will have a hard time testing the Car without the engine. You'll have to use reflection in order to exchange the instance by a mock.
If you do the following instead
class Car {
private Engine engine;
#Inject
public Car(Engine engine) {
this.engine = engine;
}
}
it is very easy to test the Car with a fake engine, replace the implementation of engine or change the way the engine should be constructed (e.g. add more parameters to the constructor).
But you should definitely use an established dependency injection framework instead of writing your own factories. If you pass in a "common factory" as Chetan suggested you end up hiding your dependencies.
Good resources for more motivation using dependency injection can be found here:
https://github.com/google/guice/wiki/Motivation or
https://youtu.be/acjvKJiOvXw (very good talk, should be worth your time).

Why do I need a FactorySupplier?

In the project I'm working on (not my project, just working on it), there are many structures like this:
project.priv.logic.MyServiceImpl.java
project.priv.service.MyServiceFactoryImpl.java
project.pub.logic.MyServiceIF.java
project.pub.service.MyServiceFactoryIF.java
project.pub.service.MyServiceFactorySupplier.java
And the Service is called like this:
MyServiceFactorySupplier.getMyServiceFactory().getMyService()
I understand that a factory is used to hide the implementation of MyServiceImpl if the location or content of MyServiceImpl changes. But why is there another factory for my factory (the supplier)? I think the probability of my Factory and my FactorySupplier to change is roughly equal. Additionally I have not found one case, where the created factory is created dynamically (I think this would be the case in the Abstract Factory Pattern) but only returns MyServiceFactoryImpl.getInstance(). Is it common practice to implement a FactorySupplier? What are the benefits?
I can think of a couple of examples (some of the quite contrived) where this pattern may be useful. Generally, you have two or more implementations for your Services e.g.
one for production use / one for testing
one implementation for services accessing a database, another one for accessing a file base storage
different implementations for different locales (translations, formatting of dates and numbers etc)
one implementation for each type of database you want to access
In each of these examples, an initialization for your FactorySupplier is needed at startup of the application, e.g. the FactorySupplier is parametrized with the locale or the database type and produces the respective factories based in these parameters.
If I understand you correctly, you don't have any kind of this code in your application, and the FactorySupplier always returns the same kind of factory.
Maybe this was done to program for extensibility that was not needed yet, but IMHO this looks rather like guessing what the application might need at some time in the future than like a conscious architecture choice.
Suppose you have a hierarchy of classes implementing MyServiceIF.
Suppose you have a matching hierarchy of factory classes to create each of the instances in the original hierarchy.
In that case, MyServiceFactorySupplier could have a registry of available factories, and you might have a call to getMyServiceFactory(parameter), where the parameter determines which factory will be instantiated (and therefore an instance of which class would be created by the factory).
I don't know if that's the use case in your project, but it's a valid use case.
Here's a code sample of what I mean :
public class MyServiceImpl implements MyServiceIF
{
....
}
public class MyServiceImpl2 implements MyServiceIF
{
....
}
public class MyServiceFactoryImpl implements MyServiceFactoryIF
{
....
public MyServiceIF getMyService ()
{
return new MyServiceImpl ();
}
....
}
public class MyServiceFactoryImpl2 implements MyServiceFactoryIF
{
....
public MyServiceIF getMyService ()
{
return new MyServiceImpl2 ();
}
....
}
public class MyServiceFactorySupplier
{
....
public static MyServiceFactoryIF getMyServiceFactory()
{
return new MyServiceFactoryImpl (); // default factory
}
public static MyServiceFactoryIF getMyServiceFactory(String type)
{
Class serviceClass = _registry.get(type);
if (serviceClass != null) {
return serviceClass.newInstance ();
} else {
return getMyServiceFactory(); // default factory
}
}
....
}
I have a related hierarchy of classes that are instantiated by a hierarchy of factories. While I don't have a FactorySupplier class, I have in the base class of the factories hierarchy a static method BaseFactory.getInstance(parameter), which returns a factory instance that depends on the passed parameter.

How to test/mock this static factory (used for graph construction)?

So, I have implemented my business classes, where I pass in all dependencies via the constructor, so I can mock those out and easily unit test them. This works great so far, but then, at one point, I need to create an object graph out of those objects. For this, I'm using a static factory (I can't use a DI framework, sadly). Example:
public class FooBar {
public FooBar(Foo foo, Bar bar) {
this.foo = foo;
this.bar = bar;
}
}
public class Foo {
public Foo() {}
}
public class Bar {
public Bar(Foo foo) {
this.foo = foo;
}
}
public class GraphFactory {
public static FooBar newFooBar() {
Foo foo = new Foo();
Bar bar = new Bar(foo);
return new FooBar(foo, bar);
}
}
So, I'm not able to really test the GraphFactory (can't mock the dependencies), which is kinda ok (not much work is done here). But what if construction of the graph is more complex, i.e. it involves looking up some properties, doing JNDI lookups and so on?
Should I still not write a unit test for this? Is my class design maybe broken? Isn't the purpose of unit testing to test classes in isolation?
There is nothing wrong with this design and it is fully testable. If we focus on the single responsibilty of the factory -- it is responsible for assembling the object graph -- the tests for this are straight forward:
Set up the factory with its prerequisites.
Invoke the factory method.
Assert that the object was constructed to your requirements: default values are set, etc.
In the example above, foo, bar, and foobar are the result of the test and do not need to be mocked.
If the assembly of the object graph is more complex, and you need additional services to fetch data and check application settings, guess what happens? These dependencies are passed into the factory through its constructor. You should mock these dependencies to isolate the factory from its dependencies' dependencies. Consumers of your factory would receive a fully wired factory through their constructor; or the factory is assembled at application start-up and made available as a singleton, etc.
This is how DI works. It sounds peculiar because now you have to worry how the factory is created (and who created that object,etc, turtles all the way down) and this is a perfectly natural reaction.
That's why we have DI frameworks to assemble complex object graphs. In a well designed DI application, nothing should know how the graph was assembled. Akin to this design, nothing should know about the DI framework.
The only exception to that rule, is... (drum-roll)... a factory object!
Most DI frameworks will inject the DI container into an object if the object being resolved takes a DI in it's constructor. This greatly simplifies the factory's plumbing, and satisfies our design principles: no one knows how to construct our object except our factory and we've encapsulated knowledge of the DI container to key areas of the application that are responsible for object assembly.
Whew. Now, if you're still following along, how does this change our test? It shouldn't, at least not too much: step #1 changes slightly, where you fill the DI container with mock objects, and then construct the factory with the DI container.
As a matter of taste, some like to use auto-mocking DI containers during testing that will automatically generate mock dependencies when an item is requested. This can remove most of the set up pain.
If the newFooBar method had to be more complex, you could refactor out everything except for the creation of the Foo and the Bar into a package-private initialisation method. Then write tests for the initialisation method.
public class GraphFactory {
public static FooBar newFooBar() {
Foo foo = new Foo();
Bar bar = new Bar(foo);
FooBar toReturn = new FooBar(foo, bar);
initialise( toReturn );
return toReturn;
}
static void initialise( FooBar toInitialise ){
// some stuff here that you can test
}
}
You can't mock or stub static method calls but you can write a unit test for the factory without mocks.
But, why do you use static factory methods?. May be better to store the factory in a static variable if you want to access it in a static way.
You should give a look into Dependecy Injection, which will allow you get rid of the factory when used properly. I recommend you this video as an introduction, it helped me a lot:
http://code.google.com/p/google-guice/
It's an introduction to Guice, a library from google, but it will help you understand DI. Then you'll see how to replace all those 'new' with annotations, letting the library do all the work for you. Some people would recommend Sring instead, but i find Guice more friendly for beginners. I just hope this doesn't fire a Guice vs Spring discussion again :D

Categories

Resources