Should you Use Constructor or Factory Method?

Pradeesh Kumar
2 min readFeb 2, 2023

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

  1. The name of the constructor must match the name of the class, hence you cannot give a meaningful name to the constructor
  2. 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.
  3. 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…

--

--

Pradeesh Kumar
Pradeesh Kumar

Written by Pradeesh Kumar

Distributed Systems | Cloud Computing | Databases | Software Engineering

Responses (1)