Go Builder Pattern — Builder Parameters

Surya Reddy
2 min readJan 11, 2021

--

So in the previous blog, we talked about Builder facets. In this blog, let's understand the Builder parameters.

Builder Parameters

What?

Builder parameters help us to restrict usage of struct properties and functions directly.

Why?

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!

Sure!

Imagine, we have to create a new feature which can send emails, and you don’t want your developers to start messing with your email object. You hide it with Builder parameters.

We see that we have a utility function SendEmail that takes a func (action) as a parameter and executes some functions like To(value string), 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!

Explanation

When 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.

Next:

Functional Builders: https://medium.com/@devcharmander/go-builder-pattern-the-functional-way-e40f347017ce

Previous:

Builder Facets: https://devcharmander.medium.com/design-patterns-in-golang-the-builder-dac468a71194

--

--