iTranslated by AI
I Created a CLI Tool to Automatically Generate Functional Options Pattern Code from Go Struct Definitions
When you want to implement optional arguments in Go, the Functional Options Pattern (FOP) is commonly used. While this design pattern is convenient, it often requires writing a significant amount of boilerplate code, as you must implement an option function for every field in a struct that you want to provide as an optional argument.
To solve this problem, I created a CLI tool called "foggo" that automatically generates the code needed to implement the Functional Options Pattern.
What is the Functional Options Pattern?
Go does not provide native support for optional arguments due to its simple language specifications.
Optional arguments, sometimes called default arguments or optional parameters, refer to variable-length arguments like *args or *kargs in Python.
While this is rarely an issue for standard functions, there are times when you want these optional arguments when providing struct initialization functions or libraries.
The Functional Options Pattern (FOP) is what is used in Go to achieve these optional arguments.
FOP is introduced in resources such as the uber Go Style Guide and go-patterns.
Below is an example of FOP as presented in go-patterns.
In FOP, you define a struct for options, higher-order functions that return functions for assigning values to option parameters, and an initialization function that takes the higher-order functions as variadic arguments. Users execute the initialization function by specifying the option functions as arguments.
// Options
package file
type Options struct {
UID int
GID int
Flags int
Contents string
Permissions os.FileMode
}
type Option func(*Options)
func UID(userID int) Option {
return func(args *Options) {
args.UID = userID
}
}
func GID(groupID int) Option {
return func(args *Options) {
args.GID = groupID
}
}
// Contents, Permissions omitted
// Constructor
func New(filepath string, setters ...Option) error {
// Default Options
args := &Options{
UID: os.Getuid(),
GID: os.Getgid(),
Contents: "",
Permissions: 0666,
Flags: os.O_CREATE | os.O_EXCL | os.O_WRONLY,
}
for _, setter := range setters {
setter(args)
}
f, err := os.OpenFile(filepath, args.Flags, args.Permissions)
if err != nil {
return err
} else {
defer f.Close()
}
if _, err := f.WriteString(args.Contents); err != nil {
return err
}
return f.Chown(args.UID, args.GID)
}
// Usage
// emptyFile, err := file.New("/tmp/empty.txt")
// fillerFile, err := file.New("/tmp/file.txt", file.UID(1000), file.Contents("Lorem Ipsum Dolor Amet"))
Additionally, with the implementation method of FOP shown above, there is an issue where tests using mocks cannot be easily performed because the optional arguments are defined as functions.
The following articles suggest an FOP pattern that resolves this issue.
(Please refer to the articles below for the specific problems.)
These articles introduce a method of defining optional arguments as "structs that hold option parameters and an apply function."
package file
type Options struct {
UID int
GID int
Flags int
Contents string
Permissions os.FileMode
}
type Option interface {
apply(*Options)
}
type UIDOption struct {
UID int
}
func (o UIDOption) apply(s *Options) {
s.UID = o.UID
}
type GIDOption struct {
GID int
}
func (o GIDOption) apply(s *Options) {
s.GID = o.GID
}
// (Contents, Permissions omitted)
func New(filepath string, setters ...Option) error {
// Duplicated parts omitted
...
for _, setter := range setters {
setter.apply(args)
}
...
return f.Chown(args.UID, args.GID)
}
Challenges with Functional Options Pattern Implementation
Because FOP requires implementing a "higher-order function to assign parameters" or an "option struct + apply function" for every single option, the implementation becomes bloated as the number of options increases.
Furthermore, optional arguments are defined using higher-order functions or functions (apply) that assign struct parameters to function arguments, which can be somewhat difficult to grasp for beginners. It might be intimidating to adopt until one fully understands it.
To eliminate this verbosity and lower the hurdle to adoption, I created a CLI tool that automatically generates FOP from struct definitions.
Introducing foggo
foggo allows you to automatically generate FOP from Go struct definitions. You can install it using go install as follows:
# foggo uses goimports to format generated code, so please install it first.
$ go install golang.org/x/tools/cmd/goimports@latest
$ go install github.com/s14t284/foggo@latest
foggo provides two subcommands: fop and afop.
fop can automatically generate code for the pattern first mentioned in the FOP introduction.
afop can automatically generate FOP code that implements the apply function. Since this article referred to the FOP that implements the apply function as the Applicable Functional Options Pattern, I used afop as the abbreviation.
Usage
foggo supports both command-line generation and generation via go:generate. Here, I will introduce how to generate FOP using go:generate.
First, define the struct for which you want to prepare option parameters as follows. Add go:generate foggo fop --struct {StructName} to the file where you have defined the function you want to automatically generate the struct for.
package file
//go:generate foggo fop --struct Options
type Options struct {
UID int
GID int
// Use the `foggo:"-"` tag for parameters you do not want to create options for
Flags int `foggo:"-"`
Contents string
Permissions os.FileMode
}
Next, run the go generate command.
$ go generate ./...
After execution, you should find code similar to the following generated in file/options_gen.go:
// Code generated by foggo; DO NOT EDIT.
package file
import "os"
type OptionsOption func(*Options)
func NewOptions(options ...OptionsOption) *Options {
s := &Options{}
for _, option := range options {
option(s)
}
return s
}
func WithUID(UID int) OptionsOption {
return func(args *Options) {
args.UID = UID
}
}
func WithGID(GID int) OptionsOption {
return func(args *Options) {
args.GID = GID
}
}
func WithPermissions(Permissions os.FileMode) OptionsOption {
return func(args *Options) {
args.Permissions = Permissions
}
}
Now, implement your code using the generated initialization function and options as needed.
To replicate the go-patterns FOP implementation example, you need to implement a function that performs file opening and writing using the options, in addition to the option initialization function.
package file
func NewFile(filepath string, options *Options) error {
flags := os.O_CREATE | os.O_EXCL | os.O_WRONLY
f, err := os.OpenFile(filepath, flags, options.Permissions)
if err != nil {
return err
} else {
defer f.Close()
}
if _, err := f.WriteString(options.Contents); err != nil {
return err
}
return f.Chown(options.UID, options.GID)
}
// It is good practice to prepare a function that initializes the struct by narrowing down the options as needed, like the one below.
func NewFileWithContentAndPermissions(filepath, content string, permissions os.FileMode) error {
options := NewOptions(
WithUID(os.Getuid()),
WithGID(os.Getgid()),
WithContents(content),
WithPermissions(permissions),
)
return NewFile(filepath, options)
}
Please check the README for examples of running the afop command.
Points to Note
Due to the nature of code generation, there are some challenges:
- Since it automatically generates functions that only accept variadic arguments, you need to implement separate functions if you require functions with non-optional arguments.
- Because default values cannot be defined within the option initialization function, it can be difficult to tell which values are defaults.
Even so, I believe it is meaningful to reduce the amount of code that must be written to realize FOP. If anyone has a solution for this, I would appreciate your feedback.
Conclusion
That was an introduction to foggo, a CLI tool that automatically generates FOP! I hope that at least one person is freed from the mundane tasks involved in implementing FOP by using foggo. If you have any improvement suggestions, I would welcome your PRs or Issues.
References
- Expert's Guide to Go (I learned about FOP and code generation from this book)
- gonstructor (A CLI that automatically generates constructors. I got the inspiration for foggo from this tool)
Discussion