Factory
A factory is a function that creates objects for you. The caller asks for a product; the factory chooses the constructor, the defaults, and the wiring.
Detailed Explanation
new User(email) couples the caller to a class and its arguments. A factory (createUser({ email }), User.fromJson(row), createTransport(kind)) hides that. It can return a class instance, a plain object, or one of several subtypes.
JavaScript factories are everywhere because class is optional. document.createElement("div") is a factory. fs.createReadStream is a factory. Promise.resolve is a factory. A function that returns { deposit, read } from a closure is a factory.
Three common forms:
- Simple factory: one function,
if (type === "admin") return new Admin. - Static factory:
User.fromEmail(email)on the class. - Abstract factory: an object that groups several create methods (
createButton,createInput) so a theme can swap all of them. Rare in small JS apps; common in UI kits.
Factories are the right place for validation, defaults, and dependency injection (createApp({ db, clock })). Tests pass a fake clock. Production passes Date.now.
What it costs you: an extra name to learn, and factories that grow into god functions. If createUser takes twenty flags, you wanted a builder or two functions. Returning different shapes from one factory without a shared interface makes callers use if ("admin" in user).
Reach for a factory when new is too low-level or when the concrete type depends on input. Reach for new when the class is the API. Reach for a singleton factory only when there must be one instance; do not hide a global inside create by accident.
Named factories beat boolean soup. createAdmin(email) and createMember(email) are clearer than createUser(email, { admin: true, verified: true, sendMail: false }). When flags start to multiply, split the function or take a small options object with defaults documented in one place.
Async factories should not leave half-built singletons on failure. If connect() throws, the next call must try again, not return the rejected promise forever unless you intend that.
Code Examples
function createUser({ email, role = "member" }) {
if (!email.includes("@")) throw new Error("bad email");
return { email, role, createdAt: Date.now() };
}
console.log(createUser({ email: "ada@example.com" }).role); // => memberclass Admin {
constructor(email) {
this.email = email;
this.role = "admin";
}
}
class Member {
constructor(email) {
this.email = email;
this.role = "member";
}
}
function createAccount(email, role) {
return role === "admin" ? new Admin(email) : new Member(email);
}
console.log(createAccount("a@x.com", "admin") instanceof Admin); // => trueclass User {
constructor(email) {
this.email = email;
}
static fromRow(row) {
return new User(row.email);
}
}
console.log(User.fromRow({ email: "b@x.com" }).email); // => b@x.comCommon Gotchas
A factory that caches and always returns the same object is a singleton
document that, or callers will mutate shared state.
Mixed return types need a shared contract
otherwise every caller switches on `role`.
`async` factories are normal
`createPool()` that `await`s a connection should return a promise and be named to show that.
Static `fromX` stays subclass-friendly if it uses `new this`
Static `fromX` stays subclass-friendly if it uses `new this`