Go Builder Pattern — Builder Parameters
So in the previous blog, we talked about Builder facets. In this blog, let's understand the Builder parameters.
Builder parameters help us to restrict usage of struct properties and functions directly.
Sometimes we want to restrict users from accessing the properties and functions of a struct directly.
We provide them with our APIs instead.
Show me the code!
Imagine, we have to create a new feature which can send emails, and you don’t want your developers to start messing with your
We see that we have a utility function
SendEmail that takes a
func (action) as a parameter and executes some functions like
From(value string) etc.
Also, notice that we don’t have access to the email struct nor the actual function that sends an email.
We start with creating a private struct and a private function
Now we define our builder struct and utility function
and finally, we define our member functions.
Putting it all together!
SendEmail() is invoked, a builder object is created(line-29) and that object’s reference is passed to an action(line-69). All the member functions of the builder are executed(71–74) and a private
sendEmail() (line-31) is called at the end.
Notice that there are implicit validations in place for email ids (37 and 48).
The user can use this API without bothering about the implementation and validation logic to create a complex object.
Functional Builders: https://medium.com/@devcharmander/go-builder-pattern-the-functional-way-e40f347017ce