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.
Features
- Effortless Code Generation: Automatically generate FOP or AFOP code from defined struct types.
- Customizable Options: Utilize options to set struct fields conveniently and cleanly without cluttering function signatures.
How It Works
To leverage foggo, define a struct type and use the foggo command to generate the corresponding code. Below is a step-by-step guide:
Example Struct Definition
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
}
Generate Functional Option Pattern Code
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...
Write Golang Code Using FOP
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"
}
Applicable Functional Option Pattern Generation
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.
Practical Benefits of FOP and AFOP
- Enhanced Readability: Options are clearly defined, making function calls self-documenting.
- Testability: Allows for easier unit testing of options.
- Flexibility: Easily add or remove options without modifying the function signature.
Learn More
For more detailed information, refer to the following articles on the Functional Option Pattern and Applicable Functional Option Pattern:
- Functional Options for Friendly APIs
- [Guide to Functional Option Pattern](https://github.com/uber-go/guide/blob/master/style.
No comments yet.
Sign in to be the first to comment.