Builder: Constructing Complex Objects Step by Step
Design Patterns Explained: From Theory to Practice: Article 4
Creating an object is usually straightforward. Creating an object with many configuration options, optional properties and rules about how those properties fit together can be considerably more complicated.
Imagine a ticket-management application where a support ticket contains a title, description, requester, priority, category, assignee, due date and a collection of tags.
Some of these properties are mandatory. Others are optional. Certain combinations may also depend on the type of ticket being created.
We could add all these properties to a constructor:
var ticket = new Ticket(
title,
description,
requesterId,
priority,
category,
assigneeId,
dueAt,
tags);
As the number of properties increases, the constructor becomes harder to read and maintain. Adding more optional parameters can make things worse, particularly when callers have to remember the correct order of arguments or supply values that are not relevant to their particular use case.
Another approach is to create an object using a parameterless constructor and assign properties afterwards. However, this can expose partially configured objects and spread validation across different parts of the application.
We need a way to control the construction process without making the object itself responsible for every possible configuration.
This is where the Builder pattern becomes useful.
What is the Builder pattern?
Builder is a creational design pattern that separates the construction of a complex object from its final representation.
It allows an object to be constructed step by step, using only the construction steps required for a particular configuration.
The pattern can also use different builders to produce different representations through a shared construction process.
In our ticket-management application, a builder can control how a ticket is configured, ensure mandatory information is provided and prevent the application from receiving an unfinished ticket.
Rather than passing every possible value into a constructor, the client describes the object it wants to create through a series of construction steps.
Understanding the structure
The traditional Builder pattern has five main participants:
| Participant | Ticket-management example | Responsibility |
|---|---|---|
| Product | Ticket |
The final object being constructed |
| Builder | ITicketBuilder |
Defines the available construction steps |
| Concrete Builder | TicketBuilder |
Implements the construction steps and assembles the ticket |
| Director | TicketCreationDirector |
Defines reusable sequences of construction steps |
| Client | TicketManagementService |
Selects a builder and initiates construction |
The key distinction is between the builder and the director.
The builder knows how to perform individual construction steps. It maintains the state of the object being assembled and produces the final result.
The director knows which steps to execute and in what order. It can encapsulate reusable construction routines, such as creating a standard support ticket or a critical incident.
The director is optional. A client can interact directly with a builder when it needs more control over the construction process.
Another important feature is that the product does not need to be exposed while it is being assembled. The client retrieves the completed object only after the construction process has finished.
Implementing Builder in C#
Let's implement the pattern using our ticket-management application.
For this example, a ticket has three mandatory properties: title, description and requester ID. Priority and category have default values, while assignee, due date and tags are optional.
Step 1: Define the product
First, define the Ticket class.
public enum TicketPriority
{
Low,
Normal,
High,
Critical
}
public enum TicketCategory
{
General,
Access,
Incident,
Billing
}
public sealed class Ticket
{
internal Ticket(
string title,
string description,
Guid requesterId,
TicketPriority priority,
TicketCategory category,
Guid? assigneeId,
DateTimeOffset? dueAt,
IReadOnlyCollection<string> tags)
{
Id = Guid.NewGuid();
Title = title;
Description = description;
RequesterId = requesterId;
Priority = priority;
Category = category;
AssigneeId = assigneeId;
DueAt = dueAt;
Tags = Array.AsReadOnly(tags.ToArray());
}
public Guid Id { get; }
public string Title { get; }
public string Description { get; }
public Guid RequesterId { get; }
public TicketPriority Priority { get; }
public TicketCategory Category { get; }
public Guid? AssigneeId { get; }
public DateTimeOffset? DueAt { get; }
public IReadOnlyList<string> Tags { get; }
}
Notice that the constructor is internal and the properties are read-only.
This is intentional. The example expects the builder to be the construction mechanism used by application code, and the finished ticket cannot be modified through its public properties.
The Tags property also deserves attention. The constructor creates a copy of the supplied collection and exposes it through a read-only view. Callers can inspect the tags but cannot add or remove items through that collection.
The model represents the completed product, not the process used to create it.
Step 2: Define the builder interface
Next, define the construction steps through an interface.
public interface ITicketBuilder
{
ITicketBuilder Reset();
ITicketBuilder WithTitle(string title);
ITicketBuilder WithDescription(string description);
ITicketBuilder RequestedBy(Guid requesterId);
ITicketBuilder WithPriority(TicketPriority priority);
ITicketBuilder WithCategory(TicketCategory category);
ITicketBuilder AssignTo(Guid assigneeId);
ITicketBuilder WithDueDate(DateTimeOffset dueAt);
ITicketBuilder AddTag(string tag);
Ticket Build();
}
Each method represents a construction operation.
The Reset() method prepares the builder for a new ticket. The Build() method validates the accumulated information and returns the completed product.
The methods return ITicketBuilder, allowing us to chain construction steps. This is known as a fluent interface.
Fluent syntax makes the API easier to read, but it is not what defines the Builder pattern. The important part is that construction has been separated from the product itself.
Step 3: Implement the concrete builder
Now implement ITicketBuilder.
The concrete builder maintains the state of the object while it is being constructed.
public sealed class TicketBuilder : ITicketBuilder
{
private string? _title;
private string? _description;
private Guid? _requesterId;
private TicketPriority _priority;
private TicketCategory _category;
private Guid? _assigneeId;
private DateTimeOffset? _dueAt;
private readonly List<string> _tags = new();
public TicketBuilder()
{
Reset();
}
public ITicketBuilder Reset()
{
_title = null;
_description = null;
_requesterId = null;
_priority = TicketPriority.Normal;
_category = TicketCategory.General;
_assigneeId = null;
_dueAt = null;
_tags.Clear();
return this;
}
public ITicketBuilder WithTitle(string title)
{
_title = title;
return this;
}
public ITicketBuilder WithDescription(string description)
{
_description = description;
return this;
}
public ITicketBuilder RequestedBy(Guid requesterId)
{
_requesterId = requesterId;
return this;
}
public ITicketBuilder WithPriority(TicketPriority priority)
{
_priority = priority;
return this;
}
public ITicketBuilder WithCategory(TicketCategory category)
{
_category = category;
return this;
}
public ITicketBuilder AssignTo(Guid assigneeId)
{
_assigneeId = assigneeId;
return this;
}
public ITicketBuilder WithDueDate(DateTimeOffset dueAt)
{
_dueAt = dueAt;
return this;
}
public ITicketBuilder AddTag(string tag)
{
if (string.IsNullOrWhiteSpace(tag))
{
throw new ArgumentException(
"A tag cannot be empty.",
nameof(tag));
}
_tags.Add(tag.Trim());
return this;
}
public Ticket Build()
{
var title = _title;
var description = _description;
var requesterId = _requesterId;
if (string.IsNullOrWhiteSpace(title))
{
throw new InvalidOperationException(
"A ticket title is required.");
}
if (string.IsNullOrWhiteSpace(description))
{
throw new InvalidOperationException(
"A ticket description is required.");
}
if (requesterId is null || requesterId == Guid.Empty)
{
throw new InvalidOperationException(
"A valid requester is required.");
}
var ticket = new Ticket(
title,
description,
requesterId.Value,
_priority,
_category,
_assigneeId,
_dueAt,
_tags.ToArray());
Reset();
return ticket;
}
}
There are several important details here.
First, the builder stores the values as construction progresses. It does not expose the unfinished Ticket object to the client.
Second, validation happens when Build() is called. This provides a central place to check that the mandatory information has been supplied before creating the product.
Third, the builder applies sensible defaults. A ticket does not need an explicitly supplied priority or category unless the caller wants to override those defaults.
Finally, the builder resets its internal state after producing a ticket. This prevents values from a previous construction from accidentally carrying over into the next one.
Resetting after Build() is a design choice rather than a strict requirement. A builder could instead require an explicit reset before reuse.
Step 4: Introduce the director
We can use a director to define reusable construction sequences.
For example, our application might regularly create standard support tickets and critical incidents.
Rather than repeating the same configuration steps throughout the application, we can encapsulate them in a director.
public sealed class TicketCreationDirector
{
public Ticket CreateStandardTicket(
ITicketBuilder builder,
string title,
string description,
Guid requesterId)
{
return builder.Reset()
.WithTitle(title)
.WithDescription(description)
.RequestedBy(requesterId)
.WithPriority(TicketPriority.Normal)
.WithCategory(TicketCategory.General)
.Build();
}
public Ticket CreateCriticalIncident(
ITicketBuilder builder,
string title,
string description,
Guid requesterId,
DateTimeOffset dueAt)
{
return builder.Reset()
.WithTitle(title)
.WithDescription(description)
.RequestedBy(requesterId)
.WithPriority(TicketPriority.Critical)
.WithCategory(TicketCategory.Incident)
.WithDueDate(dueAt)
.AddTag("incident")
.Build();
}
}
The director does not know the internal details of TicketBuilder. It only knows the construction steps exposed through ITicketBuilder.
This means we can reuse the same construction sequence with different concrete builders if the application later needs alternative representations of a ticket.
For example, a different builder could use the same steps to produce a ticket-creation document or another representation of the ticket.
Step 5: Use the builder
The client can now use the director to create predefined ticket configurations.
ITicketBuilder builder = new TicketBuilder();
var director = new TicketCreationDirector();
var ticket = director.CreateCriticalIncident(
builder,
"Payment service unavailable",
"Customers cannot complete online payments.",
requesterId,
DateTimeOffset.UtcNow.AddHours(2));
The client does not need to know how the ticket is constructed internally. It only needs to provide the information required for the selected construction routine.
Alternatively, the client can use the builder directly when it needs a custom configuration:
var ticket = new TicketBuilder()
.WithTitle("Unable to access account")
.WithDescription("The user cannot sign in.")
.RequestedBy(requesterId)
.WithPriority(TicketPriority.High)
.WithCategory(TicketCategory.Access)
.AssignTo(assigneeId)
.AddTag("authentication")
.AddTag("customer-facing")
.Build();
This is one of the main benefits of the pattern. We can support predefined construction processes through the director while still allowing clients to configure products directly when necessary.
When should you use Builder?
Builder is particularly useful when object construction involves multiple steps, optional configuration or validation rules.
Common scenarios include:
- Complex domain objects: Creating tickets, orders, invoices or other objects with several required and optional properties.
- Configuration objects: Constructing HTTP clients, database connections or application settings with many configuration options.
- Test data: Building test objects with sensible defaults while allowing individual tests to override only the properties they need.
- Complex object structures: Constructing nested objects, trees or other structures where the order of construction matters.
- Multiple representations: Using the same construction process to produce different representations of a product.
The pattern is most valuable when object construction has become a responsibility of its own rather than a simple assignment of property values.
A class with three straightforward properties does not automatically need a builder.
Advantages and disadvantages
Builder offers several benefits, but it also introduces additional complexity.
Advantages
- Improved readability: Named construction steps are easier to understand than constructors with many positional arguments.
- Controlled construction: The builder can centralise validation and prevent incomplete products from being created.
- Flexible configuration: Clients can specify only the steps relevant to the desired product.
- Reusable construction processes: Directors can define and reuse common configurations.
- Separation of responsibilities: The product represents the finished object, while the builder handles its construction.
Disadvantages
- Additional classes and interfaces: A simple object may become unnecessarily complicated when a builder is introduced.
- More code to maintain: Every new construction step may require changes to the builder contract and its implementations.
- Mutable construction state: Builders commonly maintain state while constructing an object, which requires care when instances are reused or shared.
- Potential duplication: Multiple concrete builders may repeat construction logic if their responsibilities are not designed carefully.
The pattern should make construction easier to understand and maintain. It should not simply move a complicated constructor into another class without providing a meaningful benefit.
Builder in modern C# applications
One important consideration when implementing Builder in C# is that the language already provides several features that make object construction easier.
Object initialisers allow properties to be assigned when an object is created. The init accessor restricts property assignment to the initialisation process, while the required modifier forces callers to initialise specified members. The required feature was introduced in C# 11.
For example:
public sealed class TicketDraft
{
public required string Title { get; init; }
public required string Description { get; init; }
public required Guid RequesterId { get; init; }
public TicketPriority Priority { get; init; }
= TicketPriority.Normal;
public TicketCategory Category { get; init; }
= TicketCategory.General;
public Guid? AssigneeId { get; init; }
public DateTimeOffset? DueAt { get; init; }
}
A caller can initialise this object using an object initialiser:
var ticketDraft = new TicketDraft
{
Title = "Payment service unavailable",
Description = "Customers cannot complete online payments.",
RequesterId = requesterId,
Priority = TicketPriority.Critical,
Category = TicketCategory.Incident
};
For a straightforward data object, this may be perfectly sufficient.
However, there is an important distinction.
The required modifier ensures that specified members are initialised at compile time. It does not, by itself, enforce domain validation or coordinate a multi-step construction process. Similarly, init restricts when a property can be assigned, but it does not define the sequence or rules for constructing a complex object.
This is where Builder can still provide value.
For example, if creating a critical incident requires a particular combination of priority, category, due date and tags, a builder or director can encapsulate those rules in a reusable construction process.
There is also a practical consideration with the implementation shown earlier: TicketBuilder maintains mutable state. It should be created for an individual construction operation rather than shared as a singleton across concurrent requests. The builder's lifetime and reuse strategy should reflect that statefulness.
The choice is not between using modern C# features and using design patterns. They can complement each other. The important thing is to choose the simplest approach that adequately protects the construction rules.
Builder vs Factory Method vs Abstract Factory
All three patterns belong to the creational family, but they solve different problems.
| Pattern | Main responsibility | Typical question |
|---|---|---|
| Factory Method | Delegates the choice of concrete product creation | Which implementation should be created? |
| Abstract Factory | Creates families of related products | Which compatible set of objects should be created? |
| Builder | Controls the step-by-step construction of a complex product | How should this object be assembled? |
Factory Method focuses on deciding which concrete product to create.
Abstract Factory focuses on creating related products that belong together.
Builder focuses on how a complex object is assembled.
These patterns can sometimes be combined, but they should not be treated as interchangeable solutions to every object-creation problem.
Conclusion
Builder helps us separate complex object construction from the object itself.
Our ticket-management application provides a controlled way to create tickets with different configurations while keeping validation and construction logic out of the client code.
The director makes it possible to reuse common construction sequences, while direct access to the builder allows more customised configurations.
However, Builder is not automatically the right choice whenever a constructor has several parameters. Modern C# already provides object initialisers, required properties and init accessors that may be sufficient for simpler cases.
The real skill is recognising when construction has become complex enough to justify its own abstraction.
The next article in the series explores Prototype, another creational pattern that approaches object creation differently: instead of assembling a new object step by step, it creates new objects by copying existing instances.
Further reading
Comments
Join the discussionNo comments yet. Be the first to comment.