In this article, I’d like to present you the Builder pattern and how I use it in my C# code.
The Builder Pattern is a Creational design pattern, like the Factory Method Pattern I already covered un this previous article. Its main focus is to provide a light DSL to build objects by settings startup properties, by seperating the process of constructing an object from the object itself.
Basically, the idea is to create a class with mutable fields, that will be initialized with dedicated methods, and a final method that create the object itself from thoses values. Here is an abstract example :
This class is pretty straight forward : it’s an immutable object that perform some behavior. Nothing wrong here, but it’s construction elsewhere in the code can be a little painful, because we have to know how this class works internally to give the correct parameters to its constructor.
How can we enhance this construction, how can we make this kind of code more readable therefore more maintainable?
This is the purpose of the Builder Pattern. It will allow you to craft a nice and intent-revealing way to build your object :
Note that all the builder’s methods return the builder itself, so we can compose a Fluent Interface that will improve the readability, again.
Our code could now seem more than before, but we actually gain a lot of simplicity, and we don’t need to dive into the MyClass definition anymore to know how it behaves.
I will soon post a less theorical article about this pattern, keep in touch!