I consider Joshua Bloch’s Effective Java the best book on the language that I read. However, I started to wonder about something
One of the things he suggested was to prefer public static factory methods instead of public constructors. He mentioned, among others, two advantages
- a factory method doesn’t have to create a new instance each time, instead it can return cached instances
- a factory method can return any subtype of its return type providing more flexibility
But isn’t that all a DI concern?
It made total sense when I was only learning Java, but now I start to look at it differently. Managing instances, returning proxies, it’s what DI frameworks like Spring do. Should we really allow Bloch’s “embedded DI” in our classes in addition to (let alone in place of) that framework-based DI?
Did “factory methods” become an anti-pattern, as singletons did (and for a similar reason — we decided to delegate instance management to DI frameworks to provide a better separation of concerns)?
// here, Dagger is all alone responsible for instance management
@Provides
@Singleton
public MyClass myClass() {
return new MyClass("My Class Instance", 42);
}
// here, instance management may be performed by both Dagger and the class itself
@Provides
@Singleton
public MyClass myClass() {
return MyClass.of("My Class Instance", 42);
}
demavi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.