views:

124

answers:

2

Our application makes heavy use of factories to spit out objects, but I often wonder if they are always really necessary, and it wouldn't simply be better to create an instance of a "known object" as a bean. The argument is that developers are often customizing the implementation of these returned objects (which are returned with their interface type), and since we don't technically "know" exactly what we're getting, it is better to use the factory. I'm at the point where I need to create a factory, which requires the interface, the class implementation, and then the factory. My object isn't going to change though -- it really is a concrete object with a specific purpose... shouldn't I just instantiate a bean that gets and sets the state? I'm trying to avoid premature generalization.

+3  A: 

The whole purpose of a factory or dependency injection solution is reduce coupling between the client and the runtime type of the object. It's true that the client has to know the interface and the source of the data, but now the source is free to return any type that implements the interface. It also allows you to encapsulate the knowledge of the runtime type in one place - only the factory or dependency injection solution needs to know.

This is helpful when generating runtime proxies to implement declarative transactions. From the client's point of view, they're dealing with the interface. The factory can generate the proxy that manages transactions for the client.

Once you type "new", the client is tied to using the compile type at runtime. Changing it means changing the client. If you have lots of places where you call "new" in your code that can be a maintenance problem.

When do I call "new"? I think it's appropriate inside a method to instantiate local objects that will be GC'd when they go out of scope. The method creates them, uses them, and then they're done. I would not use a factory or DI solution there.

Maybe you should close your factories and consider a dependency injection solution like Spring, Guice, or PicoContainer.

duffymo
re: reduce coupling/1st paragraph. In case it helps the reader, this was once known as the 'virtual constructor problem'.
Michael Easter
I might be reading too much into this, but wouldn't this then assume that all implementations instantiated with their interface's type should be a part of a factory?
hal10001
No, doesn't have to be. The java.util Collections aren't created using factories. Like all rules, there are times to break them.
duffymo
+2  A: 
cletus