Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we always use a factory instead of creating an object using the 'new' keyword?

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?

like image 893
ndh Avatar asked Oct 22 '25 06:10

ndh


1 Answers

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.

like image 91
Frank Puffer Avatar answered Oct 25 '25 05:10

Frank Puffer