I'm developing a simple tree-structured database and I'm usually setting dependencies or optional settings via a Builder (Builder pattern). Now I'm not sure when to use for instance Guice, when to use the Builder pattern and when to use a static factory method instead of the constructor itself. I've read Effective Java several times and I think it mentions at least a lot of advantages for not exposing the constructor. It's time to reread ;-)
So, do you know of cases which are clearly distinguishable? And shouldn't I expose the constructor? Thus for instance in every case write public static Foo getInstance(...) { return new Foo(...)}
?
I'm a firm believer in that you don't need to use dependency injection for everything.
For a
LookupService
it would be natural inject aDictionary
such that its implementation can be swapped out by configuration.For a
Firewall
on the other hand. It would be natural for it to create its ownFireWallRules
, perhaps through a suppliedFactory
or aBuilder
.As a guideline, inject what you need to configure, don't automatically inject everything else.
Consider a
static factory (*)
whenLists.newArrayList()
Consider
instance factories
whenAbstractFactory
design patternConsider a
builder
when(*)
Static methods are not always testable and the presence of one should in my opinion always be motivated. A typical usecase for a factory is to decrease coupling. By using astatic factory
that ability is completely lost.How are these 2 even close to comparable in your mind?
The builder pattern is used when you need to deal with classes whose constructors would have an overwhelming number of parameters (potentially optional) and this pattern makes your code easier to read and write.
Dependency Injection is an approach that facilitates loose coupling removing the dependencies of higher level classes to lower level classes. E.g. a class that needs to connect to a database does not directly create a connection but a connection is "injected" and this connection could be swapped to a different database without affecting the code using it.
I have started using builder for most of my projects and it turns out I can and have replaced all of my DI with builders and singleton.
ie:
My code has become much simpler to manage without DI.