Improve Code Readability with the Fluent Builder Pattern in C# | by Eiter Josef | Feb, 2022 | Medium

How the fluent builder pattern can make your code more readable and maintainable

Josef Eater
Photo by C Dustin on Unsplash

Initialisation via constructor

All arguments are passed into the constructor in the correct order. In this example, it isn’t very obvious what is passed in for which field. It can be assumed as the example is quite simple. However, for bigger objects with similar arguments, it might get harder to understand what is happening.

Initialisation via Object Initialiser

Compared to the constructor, the object initializer explicitly states the field names and the values ​​of the passed arguments. This makes it more explicit of what is happening. That approach is totally fine if all your fields have public setters meaning that your object is not immutable. C# 9.0 introduced the init keyword which is a specialized setter that allows setting the field’s value with the object initializer.

Piecewise Object Creation

An alternative approach would be piecewise object creation. This means you are creating an empty object first and then setting the values ​​for the fields one by one. This can be quite repetitive and requires a constructor method without any arguments.

A builder is a component that is responsible for object creation. Introducing builder components clearly separates your logic and model classes from creating and initializing the desired instance.

Example

The following class illustrates an example of the builder pattern.

Extending the builder pattern with a fluent API makes it easier to read the statement and enables you to chain the statements to end up with the object configuration you would like to have. The need to specify the builder object with every statement is not necessary anymore.

Example

The builder pattern is a great way to instantiate classes. Personally, I use this pattern mostly for testing. It is a simple way to create mock objects clearly stating the test setup for a specific scenario. Another practical example is using it for custom HttpClients which can be created with different (pre-)configurations.

Leave a Comment