32
Replace Constructor with Factory Function
Goal
Object creation goes through a named function that can validate, choose subclasses, or return cached instances.
Before the refactoring
const employee = new Employee(name, 'engineer', salary);After the refactoringfunction createEngineer(name, salary) {
return new Employee(name, 'engineer', salary);
}
const employee = createEngineer(name, salary);Savings
Construction can vary per case; consumers don't depend on which concrete class they're getting.
Note
Hides the actual class from callers — make sure your factory's name still expresses the produced shape clearly.