I've read at many places that object creation using the 'new' keyword should be avoided in general. Is there any case where creating an object directly in the client code is a better idea than using a factory class?
The point of factories is to separate object creation from object use (business logic). This is generally considered a good practice as it helps fulfill principles like Seperation of Concerns and Single Responsibility.
On the other hand factories produce overhead. You have to write (or read) more code if you use them.
I am sure there are cases where factories are not useful. One case that comes to my mind are action listener classes used in UI programming.
As always, you have to decide in each single case. Just ask yourself the question: Will it make my code easier to read and modify?
You should also distinguish between static factory methods which only produce little overhead and abstract factories which are much more complicated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With