Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what terms does new operator is considered harmful?

Factory pattern is supposed to be used when using new operator for creating object is considered harmful. In what terms does new operator is considered harmful

like image 207
Akhil Gupta Avatar asked Sep 18 '25 16:09

Akhil Gupta


1 Answers

new is not considered harmful.

If you want to create a new instance of a class, you need to use new somewhere. Whether you wrap the use of new in a factory is a design/architecture question.

What you are probably referring to is that "newing up" (create an instance by using new SomeClass(..)) instances all over the place, is usually considered bad design / bad practice. The reason for this, is that it can be harder to change the implementation in the future because all your classes are tightly coupled. A very common argument/example used is testing. If you create new instances directly in the code, it can be harder to test that code in isolation and/or use mocks of certain classes.

I recommend that you read about the arguments for (and against) using Dependency Injection.

Sometimes you cannot rely on a single instance injected into your class. Sometimes you need to be able to create a new instance (or multiple) on demand. In those cases, if you want to avoid using new directly, it makes sense to look into the various factory patterns as a means to extract the responsibility of creating a new instance.

Whether you follow such practices is entirely up to you and/or your team.

like image 73
MAV Avatar answered Sep 21 '25 05:09

MAV