Skip to main content

Builder Pattern in C#: Practical Implementation and Examples

 This pattern can be ideal approach to create complex objects

The Builder pattern is a creational design pattern that is used to construct complex objects step by step. It allows you to create different representations of an object using the same construction process.

Let’s first understand the problems that exist without using this pattern.

  1. Complex Constructor with Many Parameters

When creating objects that require many parameters, constructors can become lengthy and hard to read.

public class House
{
public House(int walls, int doors, int windows, bool hasGarage, bool hasSwimmingPool, bool hasStatues, bool hasGarden)
{
// Initialization
}
}

There are many problems if constructor have too many parameters

i) Each time we need to pass n numbers of parameters at time of object creations

ii) we need to update constructor if we need to pass one more parameter so such constructor difficult to manage

2. Constructor Overload Explosion

Sometimes we need to create overloaded constructor based on parameters, so managing multiple constructors again have some headache.

To handle different combinations of parameters, multiple constructor overloads are often created, leading to code duplication and increased maintenance.

public House(int walls, int doors) { ... }
public House(int walls, int doors, int windows) { ... }
public House(int walls, int doors, int windows, bool hasGarage) { ... }

3. Readability and Maintainability Issues:

Code that creates instances with many parameters becomes hard to read and maintain.

var house = new House(4, 2, 6, true, false, true, true);

Introduction of Builder pattern to fix those issues

The Builder pattern breaks down the construction of a complex object into simpler steps. Each step builds a part of the product, and the final step assembles the product.

public class HouseBuilder
{
private int _walls;
private int _doors;
private int _windows;
private bool _hasGarage;
private bool _hasSwimmingPool;
private bool _hasStatues;
private bool _hasGarden;

public HouseBuilder SetWalls(int walls) { _walls = walls; return this; }
public HouseBuilder SetDoors(int doors) { _doors = doors; return this; }
public HouseBuilder SetWindows(int windows) { _windows = windows; return this; }
public HouseBuilder SetGarage(bool hasGarage) { _hasGarage = hasGarage; return this; }
public HouseBuilder SetSwimmingPool(bool hasSwimmingPool) { _hasSwimmingPool = hasSwimmingPool; return this; }
public HouseBuilder SetStatues(bool hasStatues) { _hasStatues = hasStatues; return this; }
public HouseBuilder SetGarden(bool hasGarden) { _hasGarden = hasGarden; return this; }

public House Build()
{
return new House(_walls, _doors, _windows, _hasGarage, _hasSwimmingPool, _hasStatues, _hasGarden);
}
}

Object creations

var house = new HouseBuilder()
.SetWalls(4)
.SetDoors(2)
.SetWindows(6)
.SetGarage(true)
.SetSwimmingPool(false)
.SetStatues(true)
.SetGarden(true)
.Build();

Benefits

a. Creation of object with this pattern is very much readable, here we can understand what we are passing

b. We can control default values and validation from set methods

public HouseBuilder SetDoors(int doors) {
if (_door == 0) {
_doors = 4 // default value
} else {
_door = door;
}
return this;
}

c. We can make DB calls if required from setMethods

public HouseBuilder SetDoors(int doors) {
if (_door == 0) {
// Make a DB call to get default value
} else {
_door = door;
}
return this;
}

d. Object creation with Less Parameters

var house = new HouseBuilder()
.SetWalls(4)
.SetDoors(2)
.SetWindows(6)
.Build();

we have removed all bool parameters from above in this case we can set up default values if something we are not passing any parameters.

e. By using the Builder pattern, the object can be made immutable since the builder itself holds the state until the Build method is called. we can called this as this pattern Encourages Immutability

Thanks, Happy Coding and Learnings

#designpattern

#dotnet

#dotnetcore

#Design


Comments

Popular posts from this blog

Design Application using Clean Architecture

  Clean Architecture , introduced by  Robert C. Martin   (Uncle Bob), aims to create systems that are: Independent of frameworks Testable Independent of UI Independent of database Independent of any external agency Clean Architecture emphasizes separating the concerns of different parts of the system and ensuring that each part has a clear responsibility. .NET clean architecture as a development approach, available in a layered form to reduce dependency. The architecture consists of several layers, each with a specific role and dependencies that flow in one direction: from the outer layers to the inner layers. Inner most Layer is independent to its outer layer, means inner most layer does not have any references, it builds and stand independently. Dependency Rule The core principle of Clean Architecture is the  Dependency Rule , which states that source code dependencies can only point inward.  This means: Nothing in inner circle can depend on anything in an out...

How to Earn online from Medium.com

  As freelancer I started writing on medium (Tech blogs) from  Aug 2024   but I was already writing tech blogs on c-sharpcorner.com “The purpose of this post is to encourage new writers by helping them understand how they can earn as freelancers.” “Medium is a great platform for writers. When I started writing, I had no idea that I would reach the $100 benchmark in just four months. Now, I’m feeling self-inspired, as it has become a valuable source of income as a freelancer.” AUG 2024 ( $0 ) It was just beginning, and I posted 4 articles and had only few views 455 and 165 reads. During this time, I was learning about medium rules for writers and partner program. It will take some time to understand over all process. SEP 2024 ($6) As I started writing and I was getting few cents on Aug 2024, I posted 8 more articles in SEP, and it was good month because my blogs were getting noticed and I started getting claps etc. “This month, I went from $0 to $6, which was an achievemen...

Fixing High CPU Usage in .NET Core using Parallelism

  We will fix problem occurs due to incorrect use Parallelism in .NET Core To increase application performance sometimes we use process task or work extensively in Parallel and that may lead performance issue. When we do code, we should understand our requirement very carefully along with hardware resources those we have. We should code like that there should be less CPU usage and server should work without issues. In .NET Core, when you’re using parallelism (like Parallel.For, Task.WhenAll, or Task.Run), you might encounter performance issues if the number of concurrent threads or tasks exceeds what your system can efficiently handle. A common issue is high CPU usage or resource contention, which can degrade overall performance, cause excessive context switching, and even lead to thread starvation or deadlocks. Non members can access from here Effective Parallelism Strategies to Mitigate High CPU Usage in .NET Core We will fix problem occurs due to incorrect use Parallelism in .NE...