Golang - Options vs Builder Pattern

Matthias Bruns
5 min readMar 8, 2023

When it comes to creating complex objects in Golang, two patterns are commonly used: the Options pattern and the Builder pattern. Both patterns have their advantages and disadvantages, and choosing the right pattern depends on the specific needs of your project.

The Problem

Let’s say we want to create a complex object that has many optional parameters. One way to do this is to create a constructor that takes in all the parameters and provides default values for the optional ones. However, this approach has a few downsides:

  1. It can be hard to remember the order of the parameters.
  2. It can be hard to know which parameters are optional and which are required.
  3. The constructor can become very long and hard to read.

The Solution: Options Pattern

The Options pattern can be used to create objects with many optional parameters. In this pattern, we define a struct with optional parameters and provide methods to set those parameters. This pattern can be more concise than the Builder pattern and can be easier to use for objects with fewer parameters.

Example

In Golang, the Options pattern can be implemented using functional options. Functional options are functions…

--

--

Matthias Bruns

Senior Freelancer & Technical Lead Working as a Golang developer since 2020. as a mobile developer since 2013. Focussed on architecture & testability.