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

How the fluent builder sample could make your code extra readable and maintainable

Picture by C Dustin on Unsplash

Initialisation by way of Constructor

All arguments are handed into the constructor within the right order. On this instance, it isn’t very apparent what’s handed in for which subject. It may be assumed as the instance is sort of easy. Nevertheless, for greater objects with comparable arguments, it would get more durable to know what is occurring.

Initialisation by way of Object Initialiser

In comparison with the constructor, the thing initializer explicitly states the sector names and the values of the handed arguments. This makes it extra specific of what’s occurring. That strategy is completely superb if all of your fields have public setters that means that your object just isn’t immutable. C# 9.0 launched the init key phrase which is a specialised setter that enables setting the sector’s worth with the thing initializer.

Piecewise Object Creation

An alternate strategy can be piecewise object creation. This implies you’re creating an empty object first after which setting the values for the fields one after the other. This may be fairly repetitive and requires a constructor technique with none arguments.

A builder is a element that’s solely liable for object creation. Introducing builder parts clearly separates your logic and mannequin courses from creating and initializing the specified occasion.

Instance

The next class illustrates an instance of the builder sample.

Extending the builder sample with a fluent API makes it simpler to learn the assertion and allows you to chain the statements to finish up with the thing configuration you wish to have. The necessity to specify the builder object with each assertion just isn’t crucial anymore.

Instance

The builder sample is an effective way to instantiate courses. Personally, I exploit this sample principally for testing. It’s a easy approach to create mock objects clearly stating the take a look at setup for a particular situation. One other sensible instance is utilizing it for customized HttpClients which may be created with completely different (pre-)configurations.

More Posts