Build Better with the Builder Pattern in ASP.NET Core

The builder pattern is an extremely useful design pattern for efficiently constructing complex objects in ASP.NET Core applications. Rather than passing a large number of parameters to overloaded constructors, the builder pattern allows creating objects step-by-step. Builders allow centralizing all the complex creation logic in one place.

C# Builder Pattern in ASP.NET Core

Some key benefits of applying the builder pattern include:

  • Avoiding telescoping constructors when models have multiple optional parameters. Without a builder, we end up continually overloading constructors as new options are added.
  • Creating immutable model objects since all properties are set before the object is built and returned. This promotes thread-safety.
  • Improving readability and reusability of complex creation logic by encapsulating it inside the builder class.
  • Allowing optional parameters by setting defaults inside the builder instead of multiple constructors.

Implementing a Builder in ASP.NET Core

Here is an example of implementing a builder pattern for a House model in an ASP.NET Core MVC application:

public class House
{
    public int Stories { getset; }
    public int Bedrooms { getset; }
    public int Bathrooms { getset; }
    public double SquareFeet { getset; }
    public string Address { getset; }
    public bool HasBasement { getset; }
    public bool HasPool { getset; }
}
 
public class HouseBuilder
{
    private House house;
 
    public HouseBuilder()
    {
        house = new House();
    }
 
    public HouseBuilder WithStories(int count)
    {
        house.Stories = count;
        return this;
    }
 
    public HouseBuilder WithBedrooms(int count)
    {
        house.Bedrooms = count;
        return this;
    }
 
    public HouseBuilder WithSquareFeet(double area)
    {
        house.SquareFeet = area;
        return this;
    }
 
    public HouseBuilder AtAddress(string address)
    {
        house.Address = address;
        return this;
    }
 
    public House Build()
    {
        return house;
    }
}

This builder class allows constructing a House object step-by-step, setting only the parameters we need.


The builder handles immutability internally by returning new instances until the final configured object is built. Builders enable isolating all this complex logic separately from models and using code.


We can use this builder class as follows:

public House BuildHouse(FormCollection form)
{
    HouseBuilder builder = new HouseBuilder();
 
    return builder.WithStories(int.Parse(form["Stories"]))
                    .WithBedrooms(int.Parse(form["Bedrooms"]))
                    .WithSquareFeet(double.Parse(form["SquareFeet"]))
                    .AtAddress(form["Address"])
                    .Build();
}

This allows us to construct a House object step-by-step instead of passing multiple parameters to constructors.


Benefits


Using this builder patternapproach improves the code in several ways:

  1. Avoid lengthy constructors on House model
  2. Can set default values for optional parameters
  3. Creation logic is centralized in the builder
  4. Builder has fluent, readable API

The builder pattern is an extremely useful solution for centralizing complex object creation logic in ASP.NET Core applications. Using builders improves code reuse, avoids lengthy constructors, allows flexibility for future changes, and results in cleaner object initialization code.


Thank you reading article!

No comments:

Powered by Blogger.