Fluent Builder Design Pattern In C#

Fluent Builder Design Pattern

In the previous blog, we explored the Builder Design Pattern, including:

  • Product
  • Builder Interface
  • Concrete Builder
  • Director

We learned how the Builder Pattern helps solve the telescoping constructor problem and allows us to build complex objects step-by-step.

Before continuing this blog, I recomment to read the previous blog by clicking here

Fluent pattern is an extended, more efficient and modern approach to code in builder pattern.

Modern C# prefers Fluent Builder, where methods return the builder itself.

In the given approach in the builder pattern we have these problems:

  • Object creation becomes verbose as too many lines to write there.
  • Construction is scattered across multiple lines and this makes it hard to readable in single flow.

To solve the problem, we can write Fluent Builder (Interface)

A Fluent Interface means:

Fluent Builder is a variation of the Builder Pattern where builder methods return the builder itself, allowing method chaining and improving readability of object creation.

Let’s make one in our example –

Builder Interface

public interface IFluentUserBuilder
{
    IFluentUserBuilder SetName(string name);
    IFluentUserBuilder SetEmail(string email);
    IFluentUserBuilder SetPhone(string phone);
    IFluentUserBuilder SetAddress(string address);
    IFluentUserBuilder SetAge(int age);
    User Build();
}

We can see now each method will return IFluentUserBuilder itself.

Concrete Builder

 public class FluentUserBuilder : IFluentUserBuilder
 {
     private User _user = new User();
     public IFluentUserBuilder SetName(string name)
     {
         _user.Name = name;
         return this;
     }
     public IFluentUserBuilder SetEmail(string email)
     {
         _user.Email = email;
         return this;
     }
     public IFluentUserBuilder SetPhone(string phone)
     {
         _user.Phone = phone;
         return this;
     }
     public IFluentUserBuilder SetAddress(string address)
     {
         _user.Address = address;
         return this;
     }
     public IFluentUserBuilder SetAge(int Age)
     {
         _user.Age = Age;
         return this;
     }
     public User Build()
     {
         return _user;
     }
 }

Any SET method we call building the object(data), each SET will return the builder itself (with value set in the SET called) and then next SET will use the same and so on.

Now this is a concrete implementation that returns the builder itself after each set. By using this, we can chain the SETs when calling from main code.

   IFluentUserBuilder userBuilder = new FluentUserBuilder();
   User user = userBuilder
       .SetName("Avinash")
       .SetEmail("xyz@abc.com")
       .SetPhone("1234455")
       .SetAddress("123 Lorem Ipsum Dolar Amet")
       .SetAge(30)
       .Build();

We can see result of SetName it gets and then in the chain SetEmail is called then after the result of SetEmail(), SetPhone is called. This chain is more easy and quick to read and manage.

When To Use Fluent Builder Design

  • When you need to build chain of method calls for building the object.
  • When the result of one SET is useful to build next.

Real World Examples of Fluent Builder Patterns in C#

StringBuilder

var sb = new StringBuilder();
sb.Append("Hello");
sb.Append("World");

ASP.NET Core

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();

LINQ

var result = users
            .Where(x => x.Age > 18)
            .OrderBy(x => x.Name);

That’s it for the blog.

Our Next Blog will explore Immutable Builder Pattern. Click here

Read more here

Recommended Topics

Popular Tags

.net .Net Core .NET Developers .NET Development Future .NET Productivity .NET programming agentic ai AI Agents AI Tools .NET app.Map Azure AI Boilerplate Builder Design Pattern in C# C# C# AI C# Design Patterns C# Programming circuit breaker pattern Code Assistants Coding Coding best practices Coding in AI Creational Design Patterns Design Patterns Design Patterns in C# dotnet core resilience Factory Design Patterns in C# Fluent Builder Design Pattern Generative AI Immutable Builder Design Pattern In C# Knowledge Lightweight API LLMs .NET Machine Learning .NET MapGet Microservices microservices resilience ML.NET Motivational polly v8 resilience architecture REST API retry pattern Semantic Kernel Singleton Design Pattern in C# Software Architecture Step Builder Design Pattern In C# The Avinash Joshi TheAvinashJoshi Top 5 AI tools trending coding methods vibe coding Visual Studio AI Web API Web Development