[EnhanceYourCode] : the Builder Pattern

Builder

Hello,

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!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s