By Diego Liascovich
Full-Stack Developer | Microservices | Angular | Node.js
The Builder design pattern is useful when you need to construct complex objects step-by-step, especially when many optional parameters are involved.
Letβs walk through a real-world case: building a User object in a web application, where some fields are optional depending on context (e.g., user profile, registration, or admin creation).
π― Use Case
You're developing a web system where users can be created with various optional fields:
- Name
- Address
- Role
- Preferences
Using a traditional constructor with multiple parameters would be messy. The Builder pattern makes this process much cleaner.
π¦ User.ts
export class User {
public name?: string;
public email?: string;
public address?: string;
public role?: string;
public preferences?: Record<string, any>;
constructor(builder: UserBuilder) {
this.name = builder.name;
this.email = builder.email;
this.address = builder.address;
this.role = builder.role;
this.preferences = builder.preferences;
}
}
π§± UserBuilder.ts
import { User } from './User';
export class UserBuilder {
public name?: string;
public email?: string;
public address?: string;
public role?: string;
public preferences?: Record<string, any>;
setName(name: string): UserBuilder {
this.name = name;
return this;
}
setEmail(email: string): UserBuilder {
this.email = email;
return this;
}
setAddress(address: string): UserBuilder {
this.address = address;
return this;
}
setRole(role: string): UserBuilder {
this.role = role;
return this;
}
setPreferences(preferences: Record<string, any>): UserBuilder {
this.preferences = preferences;
return this;
}
build(): User {
return new User(this);
}
}
β Example Usage
import { UserBuilder } from './UserBuilder';
const user = new UserBuilder()
.setName('Alice Smith')
.setEmail('alice@example.com')
.setRole('admin')
.setPreferences({ darkMode: true, language: 'en' })
.build();
console.log(user);
π‘ Benefits of Using Builder Here
- β Readable and Fluent API: No need to deal with long parameter lists.
- β Flexible: Create different configurations of the object easily.
- β Safe and Scalable: Easy to extend as new fields are added.
π§ Final Thoughts
The Builder pattern shines when youβre working with complex object creation that needs flexibility and clarity. It helps you keep your code clean and extensible β a great choice for constructing domain models in modern TypeScript applications.
Top comments (0)