Should you Use Constructor or Factory Method?
Constructor
We have been using constructors in object-oriented programming languages such as Java, C++, etc. A constructor is a special type of static method which can be invoked using thenew
keyword and used to initialize the fields of a newly created object.
Problem with Constructors
- The name of the constructor must match the name of the class, hence you cannot give a meaningful name to the constructor
- The return type is not applicable to the constructor, hence you can always expect the object of the same class. It means you cannot return the object of its subtype of the class.
- You cannot mock a constructor for unit testing
Static factory methods
The static factory method is another way of creating and initializing an object. Using the static factory method instead of a constructor allows you to return objects of different subtypes based on the arguments, making the code more flexible and easier to understand.
Additionally, static factory methods can have more descriptive names, making the code more self-explanatory, and they can also return objects that are already created, which can help to reduce unnecessary object creation and improve…