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...

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...

Report generation in .Net Core API

  In this tutorial we will learn about quick way to generate reports using .net core api. When we work in companies, we may face a situation where client ask to generate reports, and he is not ready to spend money in purchasing third party libraries to get reports. Apart from this he want to work to done in same day or he has some urgency. In this situation this tutorial will helpful where we need to generate reports in single day without spending and wasting time in research. Let’s Start. a. We will create .Net core API. b. Create Endpoint for Download file c. Make a call to database and fetch data. d. Create report in html format and send html file back to user as response. Consider we connect to database and get below data table Consider code below using Microsoft.AspNetCore.Mvc; using System.Data; using System.Text; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace DownloadFile.Controllers { [ ...