cvanloo / rmsgo

Remote Storage implementation in Go
The Unlicense
1 stars 0 forks source link

Use Options pattern to configure server #14

Closed cvanloo closed 1 month ago

cvanloo commented 2 months ago

I think I tried that already but can't remember why I decided against it.

cvanloo commented 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),
)
cvanloo commented 1 month ago

So I think I'll stick with the builder pattern.

cvanloo commented 1 month ago

Or simpler:

func Optionally(cond bool, opt Option) Option {
    return func(c *Config) {
        if cond {
            opt(c)
        }
    }
}
cvanloo commented 1 month ago

Honestly, the solution in the comment from 3 weeks ago is just dumb, don't know what I was thinking.