Foggo simplifies the process of creating Functional Option Pattern code from Golang struct fields. By providing a streamlined command-line interface, users can generate options for their structs seamlessly, ensuring code clarity and maintainability. Ideal for Go developers looking to enhance their coding practices.
foggo is a powerful tool designed to generate code implementing the Functional Option Pattern (FOP) and Applicable Functional Option Pattern (AFOP) in Golang. This utility streamlines the process of creating functional options for struct fields, enhancing the flexibility and usability of Go applications.
To leverage foggo, define a struct type and use the foggo command to generate the corresponding code. Below is a step-by-step guide:
Prepare a struct in your Go project as shown:
package image
type Image struct {
Width int
Height int
Src string `foggo:"-"` // Exclude from options
Alt string
}
Execute the following command to generate FOP code:
$ foggo fop --struct Image --package image
This command will create a new file containing the generated FOP code like:
// Code generated by foggo; DO NOT EDIT.
package image
type ImageOption func(*Image)
func NewImage(options ...ImageOption) *Image {
s := &Image{}
for _, option := range options {
option(s)
}
return s
}
func WithWidth(Width int) ImageOption {
return func(args *Image) {
args.Width = Width
}
}
// Additional options...
Integrate the generated FOP code into your application with ease:
package main
import "github.com/user/project/image"
func main() {
img := NewImage(
WithWidth(1280),
WithHeight(720),
WithAlt("alt title"),
)
img.Src = "./image.png"
}
For generating AFOP code, simply use the afop subcommand instead:
$ foggo afop --struct Image
This process results in a testable version of FOP, where options are encapsulated as types with an apply method, improving code maintainability and testability.
For more detailed information, refer to the following articles on the Functional Option Pattern and Applicable Functional Option Pattern:
No comments yet.
Sign in to be the first to comment.