“Replace Constructor with Factory Method” is a refactoring technique used in object-oriented programming. This technique involves replacing the direct use of a constructor for object creation with a call to a factory method. A factory method is a method that returns an instance of the class.
Application of the “Replace Constructor with Factory Method” Refactoring
This technique is typically applied in the following scenarios:
- When a constructor cannot describe the meaning of the created object clearly. A factory method can have a meaningful name that describes the created object.
- When a class requires a more complex process to create an object, which cannot be accomplished with a simple constructor.
- When a class needs to return a subclass instance instead of an instance of the base class.
A Simple Example
Here is a simple example of this refactoring technique:
Before:
class Employee {
public Employee() {
// constructor logic
}
}
// Usage
Employee emp = new Employee();
JavaAfter:
class Employee {
private Employee() {
// constructor logic
}
public static Employee create() {
return new Employee();
}
}
// Usage
Employee emp = Employee.create();
JavaIn the refactored code, the constructor is made private and a static factory method create()
is introduced. This method creates and returns an instance of the Employee
class.
An Example from the Standard Java SDK
Here are some examples of factory methods from the standard Java SDK:
java.util.Calendar Class
Calendar.getInstance()
: This method from thejava.util.Calendar
class returns aCalendar
instance based on the current time in the default time zone with the defaultLocale
.Calendar.getInstance(TimeZone zone)
: This method from thejava.util.Calendar
class returns aCalendar
instance based on the current time in the givenTimeZone
with the defaultLocale
.
java.util.Collections class
emptyList()
: This factory method returns an immutable empty list.emptySet()
: This factory method returns an immutable empty set.emptyMap()
: This factory method returns an immutable empty map.
Pros and Cons of the Replace Constructor with Factory Method Refactoring
Pros:
- Factory methods have more descriptive names than constructors, which can make the code more readable.
- Factory methods can return objects of any subtype, not just objects of the type they belong to.
- Factory methods can return existing instances, which can be useful for implementing patterns like Singleton or Flyweight.
Cons:
- The main disadvantage of using factory methods is that they can make the code more complicated, especially if the creation logic is straightforward and doesn’t require any additional steps.
- Factory methods can’t be used in conjunction with subclassing. If a class has factory methods, it should usually be declared as final (in languages that support this keyword).
- Using factory methods may require changes to existing client code, which can be a disadvantage if backward compatibility is a concern.