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 ?