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.
views:
124answers:
2The 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.