7
Back to Boss Battles

BuilderVSFactory (Method/Abstract)

The Problem

Scenario A — Builder territory: You are constructing a complex query object for an analytics API. It has 12 optional fields: date range, filters, groupBy, orderBy, limit, offset, aggregations, etc. Some combinations are invalid (you cannot group by a field you also filter on). You need step-by-step construction with validation.

Scenario B — Factory territory: You need to create a database connection object. It is either a PostgresConnection or a MongoConnection. Each has a fixed constructor — you just need to pick the right class based on config.


Why They Look Alike

Both create objects. Both hide the new ConcreteClass() call from the client. Both are "creational patterns." People lump them together as "ways to create stuff."


The Fundamental Difference

Factory picks WHICH class to instantiate. Builder controls HOW a complex object is assembled step by step.

Factory: "Give me the right type." One call, object is ready. Builder: "Let me configure this piece by piece." Multiple calls, then .build().


Decision Rule

CluePattern
"Object has many optional parameters"Builder
"Need to pick between different concrete types"Factory
"Construction is multi-step with validation"Builder
"One call returns a ready-to-use object"Factory
"Same construction process, different representations"Builder
"Type varies, but each type has a simple constructor"Factory

Side-by-Side Code

Builder — step-by-step complex construction

typescript
1interface AnalyticsQuery {
2 table: string;
3 dateRange?: { start: Date; end: Date };
4 filters?: Array<{ field: string; op: string; value: unknown }>;
5 groupBy?: string[];
6 orderBy?: { field: string; direction: "asc" | "desc" };
7 limit?: number;
8}
9
10class QueryBuilder {
11 private query: Partial<AnalyticsQuery> = {};
12
13 forTable(table: string): this {
14 this.query.table = table;
15 return this;
16 }
17
18 withDateRange(start: Date, end: Date): this {
19 this.query.dateRange = { start, end };
20 return this;
21 }
22
23 filterBy(field: string, op: string, value: unknown): this {
24 this.query.filters ??= [];
25 this.query.filters.push({ field, op, value });
26 return this;
27 }
28
29 groupBy(...fields: string[]): this {
30 this.query.groupBy = fields;
31 return this;
32 }
33
34 limit(n: number): this {
35 this.query.limit = n;
36 return this;
37 }
38
39 build(): AnalyticsQuery {
40 if (!this.query.table) throw new Error("Table is required");
41 return this.query as AnalyticsQuery;
42 }
43}
44
45// Usage — step by step, fluent, readable
46const query = new QueryBuilder()
47 .forTable("events")
48 .withDateRange(new Date("2024-01-01"), new Date("2024-12-31"))
49 .filterBy("status", "=", "active")
50 .groupBy("region", "product")
51 .limit(100)
52 .build();

Factory — pick the right type in one call

typescript
1interface DbConnection {
2 connect(): Promise<void>;
3 query(sql: string): Promise<unknown>;
4}
5
6class PostgresConnection implements DbConnection {
7 constructor(private url: string) {}
8 async connect() { console.log(`PG connected to ${this.url}`); }
9 async query(sql: string) { return `PG result for: ${sql}`; }
10}
11
12class MongoConnection implements DbConnection {
13 constructor(private url: string) {}
14 async connect() { console.log(`Mongo connected to ${this.url}`); }
15 async query(sql: string) { return `Mongo result for: ${sql}`; }
16}
17
18function createConnection(config: { type: string; url: string }): DbConnection {
19 switch (config.type) {
20 case "postgres": return new PostgresConnection(config.url);
21 case "mongo": return new MongoConnection(config.url);
22 default: throw new Error(`Unknown DB: ${config.type}`);
23 }
24}
25
26// Usage — one call, object is ready
27const db = createConnection({ type: "postgres", url: "postgres://..." });

Key difference: Builder is about how to assemble a complex object. Factory is about which object to create.


Scenario Quiz

?Knowledge Check

1You're building an HTTP request object with optional headers, body, query params, timeout, retries, and auth. Which pattern?

2A config file says 'cache: redis' or 'cache: memcached'. You need to return the right cache client. Which pattern?

3A test helper creates User objects with customizable name, email, role, permissions, and avatar — all optional with sensible defaults. Which pattern?

4A notification system creates EmailNotifier or SlackNotifier based on user preference. Each has a simple constructor. Which pattern?

5TypeORM's createQueryBuilder() lets you chain .select(), .where(), .orderBy(), .leftJoin(). Which pattern is this?

6NestJS's @Module decorator creates a module. The DI container decides which provider class to instantiate based on tokens. Which pattern?

7Can Builder and Factory be combined?

8You need to construct a Docker container spec: image, ports, volumes, env vars, health check, resource limits — 15 optional fields with validation. Which pattern?