Closed cvanloo closed 1 month ago
Options pattern is not as flexible as the builder pattern, eg., conditional configuration can't easily be done, unless:
func NewFoo(opts ...Opt) *Foo {
foo := &Foo{
// setup default values
}
for _, opt := range opts {
if opt != nil { // [!] check for nil
opt(foo)
}
}
}
func Optionally(cond bool, conf func() Opt) Opt {
if cond {
return conf() // [!] we don't want the option function to be eval'd unless cond is true
}
return nil
}
foo := NewFoo(
UseXXX0(),
Optionally(bFlag1, UseXXX1),
Optionally(bFlag2, UseXXX2),
)
So I think I'll stick with the builder pattern.
Or simpler:
func Optionally(cond bool, opt Option) Option {
return func(c *Config) {
if cond {
opt(c)
}
}
}
Honestly, the solution in the comment from 3 weeks ago is just dumb, don't know what I was thinking.
I think I tried that already but can't remember why I decided against it.