Go Builder Pattern — The Functional Way
So, in my previous blogs, we talked about Builder Facets and Builder Parameters.
Read them here:
One way to extend the builder that you already have is by using a Functional Programming approach!
Let’s take the same example that we used in my previous blog.
We want to create an
Employee object step by step using a functional approach, that would look something like this!
To achieve a fluent API like this in “go” is really simple.
- We add a property to the Builder struct that takes an array of actions. (line-16)
- Every builder’s member function adds an action to the above property. (line 20–41)
Build()function iterates through all the actions and executes it on an
Employeeobject. (line 44–50)
Builder patterns are useful but sometimes can be a pain in wrong places. The upside is being able to create complex objects more easily with control over what properties to expose and what to hide from the end-user, but the downside is whenever a new property is added we need to create a new function to set the value.
Builder Facets can be used to functionally break the builder in smaller sub-builders that can work in tandem to create a complex object.
Builder Parameters can be used to have control over the properties that we want to expose to our developers.
Functional way of creating builders enable us to create fluent APIs that are easy to read.