Techniquecore
Replace constructor with factory function
Also called replace constructor with factory method.
Replace direct calls of a constructor with calls of an ordinary function that makes the object, so that the creation can have a name and can choose what to return.
- Family
- refactoring
- Intent
- Give object creation a name and free it from the limits of a constructor.
- Also called
- Replace Constructor with Factory Method
Purpose
In many languages a constructor has limits that an ordinary function does not have:
- Its name is the name of the class, so it cannot say which kind of object the caller wants.
- It must return a new instance of exactly that class. It cannot return a subclass, a cached object or a proxy.
- It needs a special call, such as
newin JavaScript, Java and C#.
Replace constructor with factory function puts a normal function in front of the constructor. The catalogue card turns new Employee(document.leadEngineer, 'E') into createEngineer(document.leadEngineer).1 The code 'E' is gone from the call, and the name says what the caller makes.
Steps
- Make a factory function. Its body calls the constructor.
- Replace each call of the constructor with a call of the factory function. Test after each change.
- If the language allows it, limit the visibility of the constructor, so that new code must use the factory function.
Example
An employee has a type code. A caller that makes an engineer must know that the code of an engineer is 'E'. After the refactoring, the caller calls createEngineer.
import assert from "node:assert/strict";
class Employee {
constructor(name, typeCode) {
this._name = name;
this._typeCode = typeCode;
}
get name() { return this._name; }
get type() { return Employee.legalTypeCodes[this._typeCode]; }
static get legalTypeCodes() { return { E: "Engineer", M: "Manager", S: "Salesperson" }; }
}
function createEmployee(name, typeCode) {
return new Employee(name, typeCode);
}
function createEngineer(name) {
return new Employee(name, "E");
}
const before = new Employee("Ana", "E");
const after = createEngineer("Ana");
assert.deepEqual(after, before);
assert.equal(createEmployee("Bo", "M").type, "Manager");
console.log(`${after.name}: ${after.type}`);
Ana: Engineer
| Language | What the example shows |
|---|---|
| JavaScript | new Employee(name, 'E') replaced with createEngineer(name), as above |
| Python | a class method Employee.engineer(name); Python has no new, and the call of a class already looks like a call of a function |
| Go | NewEngineer(name), a plain function next to NewEmployee(name, code) |
class Employee:
LEGAL_TYPE_CODES = {"E": "Engineer", "M": "Manager", "S": "Salesperson"}
def __init__(self, name: str, type_code: str) -> None:
self.name = name
self._type_code = type_code
@property
def type(self) -> str:
return self.LEGAL_TYPE_CODES[self._type_code]
@classmethod
def engineer(cls, name: str) -> "Employee":
return cls(name, "E")
before = Employee("Ana", "E")
after = Employee.engineer("Ana")
assert vars(after) == vars(before)
print(f"{after.name}: {after.type}")
Ana: Engineer
package main
import "fmt"
var legalTypeCodes = map[byte]string{'E': "Engineer", 'M': "Manager", 'S': "Salesperson"}
type Employee struct {
name string
typeCode byte
}
func NewEmployee(name string, typeCode byte) Employee {
return Employee{name: name, typeCode: typeCode}
}
func NewEngineer(name string) Employee {
return NewEmployee(name, 'E')
}
func (e Employee) Type() string { return legalTypeCodes[e.typeCode] }
func main() {
before := NewEmployee("Ana", 'E')
after := NewEngineer("Ana")
if after != before {
panic("mismatch")
}
fmt.Printf("%s: %s\n", after.name, after.Type())
}
Ana: Engineer
When to use
- The call needs a name. A code, a flag or a list of literals in a constructor call says less than a function name such as
createEngineer. See Boolean parameter. - The creation must choose the class. A factory function can return a subclass or another implementation of an interface. This is the start of Simple factory.
- The creation must reuse objects. A factory function can return a cached instance. In Java and C#,
newalways makes a new object. - The constructor must stay hidden. With a private constructor, the factory function is the only way in.
Pitfalls
Constructors in other languages. The refactoring matters most in languages where new calls the constructor. In Rust, the API Guidelines say that constructors "are just a convention". They define them as "static (no self) inherent methods for the type that they construct."5 There, and in other languages where a plain function makes the value, the factory function is already the normal style, and the refactoring is only a rename, for example from new to engineer.
Too many factory functions. One factory function for each combination of arguments makes the API large. Use them for the cases that callers use often.
Not the same as the Factory Method pattern. A factory function is a plain function. The Factory Method design pattern uses a method that subclasses override to choose the class. See Factory method and Static factory method.
Tools that do it
IntelliJ IDEA has the action Replace Constructor with Factory Method. Its documentation says that it "lets you hide a constructor and replace it with a static method which returns a new instance of a class."4
The catalogue lists the refactoring in the first edition, the second edition and the Ruby edition, with the tags refactoring-apis and grouping-function.2 In the second edition it is in Chapter 11, Refactoring APIs.3
References
- Martin Fowler, Catalog of Refactorings, Replace Constructor with Factory Function, the entry, the createEngineer sketch; aliases Replace Constructor with Factory Method
- Martin Fowler, Catalog of Refactorings, index, the entry replaceConstructorWithFactoryFunction, its books and tags
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 11, Refactoring APIs, Replace Constructor with Factory Function
- JetBrains, IntelliJ IDEA documentation, Replace constructor with factory method, the first paragraph
- Rust API Guidelines, Predictability, Constructors are static, inherent methods (C-CTOR)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag YC32KZ Edit this page History Report an error Markdown