Golang 函数式选项模式

Nov 24, 2020 21:00 · 2471 words · 5 minute read Golang

译文

作为一个 Golang 开发者一定会遇到函数入参可选这个问题。这是一个很常见的需求,有些对象要有能够开箱即用的默认配置,你可能还想提供一些更详细的配置。

很多语言都能轻而易举做到:在 C 语言家族中,同一个函数可以有不同参数的多个版本;PHP 中你可以给参数一个默认值并在调用方法时省略它们。但是 Golang 中就不能这么搞了。那么如何创建一个函数让用户随心所欲地传参呢?

有不少方法,但绝大多数都不尽如人意,要么给服务器端的代码带来大量额外的检查和验证;要么客户端传一堆无关紧要的参数。

我来介绍几样手法,并解释它们的缺点,慢慢改进,直到终极解决方案:函数式选项模式。

来看个例子。比方说我们有个叫 StuffClient 的服务,它有两个配置选项(超时和重试):

type StuffClient interface {
    DoStuff() error
}
type stuffClient struct {
    conn    Connection
    timeout int
    retries int
}

这个结构体是私有的,所以我们要提供构造函数:

func NewStuffClient(conn Connection, timeout, retries int) StuffClient {
    return &stuffClient{
        conn:    conn,
        timeout: timeout,
        retries: retries,
    }
}

这。。。我们每次调用 NewStuffClient 时都得提供 timeoutretries。大多数时间我们就只想用默认参数。不能再定义 NewStuffClient 同名函数了,编译通不过的。

另一种办法是搞几个名字不同的构造函数:

func NewStuffClient(conn Connection) StuffClient {
    return &stuffClient{
        conn:    conn,
        timeout: DEFAULT_TIMEOUT,
        retries: DEFAULT_RETRIES,
    }
}
func NewStuffClientWithOptions(conn Connection, timeout, retries int) StuffClient {
    return &stuffClient{
        conn:    conn,
        timeout: timeout,
        retries: retries,
    }
}

这看起来也太蹩脚了。我们整个更好的,传个配置对象进去:

type StuffClientOptions struct {
    Retries int //number of times to retry the request before giving up
    Timeout int //connection timeout in seconds
}
func NewStuffClient(conn Connection, options StuffClientOptions) StuffClient {
    return &stuffClient{
        conn:    conn,
        timeout: options.Timeout,
        retries: options.Retries,
    }
}

但这也不太好。现在即使不想指定任何选项也不得不创建一个配置对象并将其传递进来。而且也没有自动设置默认值,除非我们在代码中添加一堆检查,或者暴露一个 DefaultStuffClientOptions 变量来作为默认参数传递(有可能在哪里被修改的,可能会导致其他地方出问题)。

最好的解决方案是 Functional Options Pattern,利用 Go 的闭包特性。我们保留上面定义的 StuffClientOptions,还要再加点调料:

type StuffClientOption func(*StuffClientOptions)
type StuffClientOptions struct {
    Retries int //number of times to retry the request before giving up
    Timeout int //connection timeout in seconds
}
func WithRetries(r int) StuffClientOption {
    return func(o *StuffClientOptions) {
        o.Retries = r
    }
}
func WithTimeout(t int) StuffClientOption {
    return func(o *StuffClientOptions) {
        o.Timeout = t
    }
}

很晦涩吧?我是谁我从哪里来我要去哪里?我们已经定义了 StuffClient 结构的可用选项。另外又定义了一个叫 StuffClientOption 的东西,以我们的结构体为参数。我们还定义了一堆 WithRetriesWithTimeout 方法,返回闭包。现在开始我们的表演:

var defaultStuffClientOptions = StuffClientOptions{
    Retries: 3,
    Timeout: 2,
}
func NewStuffClient(conn Connection, opts ...StuffClientOption) StuffClient {
    options := defaultStuffClientOptions
    for _, o := range opts {
        o(&options)
    }
    return &stuffClient{
        conn:    conn,
        timeout: options.Timeout,
        retries: options.Retries,
    }
}

现在我们定义了一个内部的变量包含了默认选项,再调整构造器来接受非定长参数。然后遍历 StuffClientOption,将返回的闭包应用至选项变量(回调这些闭包接受一个 StuffClientOptions 变量并改值)。

现在要做的就是使用它:

x := NewStuffClient(Connection{})
fmt.Println(x) // prints &{{} 2 3}
x = NewStuffClient(
    Connection{},
    WithRetries(1),
)
fmt.Println(x) // prints &{{} 2 1}
x = NewStuffClient(
    Connection{},
    WithRetries(1),
    WithTimeout(1),
)
fmt.Println(x) // prints &{{} 1 1}

这个看起来顺眼多了。很赞的一点是我们很容易就可以添加新的选项,只要改少量代码。

把所有片段拼起来后看上去是这样的:

var defaultStuffClientOptions = StuffClientOptions{
    Retries: 3,
    Timeout: 2,
}
type StuffClientOption func(*StuffClientOptions)
type StuffClientOptions struct {
    Retries int //number of times to retry the request before giving up
    Timeout int //connection timeout in seconds
}
func WithRetries(r int) StuffClientOption {
    return func(o *StuffClientOptions) {
        o.Retries = r
    }
}
func WithTimeout(t int) StuffClientOption {
    return func(o *StuffClientOptions) {
        o.Timeout = t
    }
}
type StuffClient interface {
    DoStuff() error
}
type stuffClient struct {
    conn    Connection
    timeout int
    retries int
}
type Connection struct {}
func NewStuffClient(conn Connection, opts ...StuffClientOption) StuffClient {
    options := defaultStuffClientOptions
    for _, o := range opts {
        o(&options)
    }
        return &stuffClient{
            conn:    conn,
            timeout: options.Timeout,
            retries: options.Retries,
        }
}
func (c stuffClient) DoStuff() error {
    return nil
}

还能更简洁点,干掉 StuffClientOptions 结构,直接在 StuffClient 应用选项。

var defaultStuffClient = stuffClient{
    retries: 3,
    timeout: 2,
}
type StuffClientOption func(*stuffClient)
func WithRetries(r int) StuffClientOption {
    return func(o *stuffClient) {
        o.retries = r
    }
}
func WithTimeout(t int) StuffClientOption {
    return func(o *stuffClient) {
        o.timeout = t
    }
}
type StuffClient interface {
    DoStuff() error
}
type stuffClient struct {
    conn    Connection
    timeout int
    retries int
}
type Connection struct{}
func NewStuffClient(conn Connection, opts ...StuffClientOption) StuffClient {
    client := defaultStuffClient
    for _, o := range opts {
        o(&client)
    }

    client.conn = conn
    return client
}
func (c stuffClient) DoStuff() error {
    return nil
}

这种设计模式的普及要归功于 Rob PikeDave Cheney


原文

One of the many issues you’ll encounter as a Golang developer is trying to make parameters to a function optional. It’s a pretty common use case that you have some object which should work out-of-the-box using some basic default settings, and you may occasionally want to provide some more detailed configuration.

In many languages this is easy; in C-family languages, you can provide multiple versions of the same function with different numbers of arguments; in languages like PHP, you can give parameters a default value and omit them when calling the method. But in Golang you can’t do either of those. So how do you create a function which has some additional configuration a user can specify if they want, but only if they want to?

There are a number of possible ways to do this, but most are pretty unsatisfactory, either requiring a lot of additional checking and validating in the code on the service-side, or extra work for the client by passing in additional parameters which they don’t care about.

I’ll walk through some of the different options and show why each is suboptimal and then we’ll build our way up to our final, clean solution: the Functional Options Pattern.

Let’s take a look at an example. Let’s say we have some service called StuffClient which does some stuff and has a two configuration options (timeout and retries):

type StuffClient interface {
    DoStuff() error
}
type stuffClient struct {
    conn    Connection
    timeout int
    retries int
}

That struct is private, so we should provide some sort of constructor for it:

func NewStuffClient(conn Connection, timeout, retries int) StuffClient {
    return &stuffClient{
        conn:    conn,
        timeout: timeout,
        retries: retries,
    }
}

Hmm, but now we always have to provide the timeout and retries every time we call NewStuffClient. And most of the time we’ll want to just use the default values. We can’t define multiple versions of NewStuffClient with different numbers of parameters or else we’ll get a compile error like “NewStuffClient redeclared in this block”.

One option would be to create another constructor with a different name like:

func NewStuffClient(conn Connection) StuffClient {
    return &stuffClient{
        conn:    conn,
        timeout: DEFAULT_TIMEOUT,
        retries: DEFAULT_RETRIES,
    }
}
func NewStuffClientWithOptions(conn Connection, timeout, retries int) StuffClient {
    return &stuffClient{
        conn:    conn,
        timeout: timeout,
        retries: retries,
    }
}

But that’s kind of crappy. We can do better than that. What if we passed in a config object:

type StuffClientOptions struct {
    Retries int //number of times to retry the request before giving up
    Timeout int //connection timeout in seconds
}
func NewStuffClient(conn Connection, options StuffClientOptions) StuffClient {
    return &stuffClient{
        conn:    conn,
        timeout: options.Timeout,
        retries: options.Retries,
    }
}

But that’s also not really great. Now we always have to create this struct and pass that in even if we don’t want to specify any options. And we also don’t have the defaults automatically filled in unless we add a bunch of checks in the code somewhere or we expode a DefaultStuffClientOptions variable which we could pass in (also not nice because it could be modified in one place which could cause issues somewhere else).

So what’s the solution? The nicest way to solve this dilemma is with the Functional Options Pattern, making use of Go’s convenient support of closures. Let’s keep this StuffClientOptions we defined above, but we’ll add some things to it:

type StuffClientOption func(*StuffClientOptions)
type StuffClientOptions struct {
    Retries int //number of times to retry the request before giving up
    Timeout int //connection timeout in seconds
}
func WithRetries(r int) StuffClientOption {
    return func(o *StuffClientOptions) {
        o.Retries = r
    }
}
func WithTimeout(t int) StuffClientOption {
    return func(o *StuffClientOptions) {
        o.Timeout = t
    }
}

Clear as mud right? What’s happening here exactly? Basically we have our struct defining the available options for our StuffClient. Additionally now we’ve defined something called StuffClientOption (singular this time) which is just a function which accepts our options struct as a parameter. We’ve defined a couple of functions additionally called WithRetries and WithTimeout which return a closure. Now comes the magic:

var defaultStuffClientOptions = StuffClientOptions{
    Retries: 3,
    Timeout: 2,
}
func NewStuffClient(conn Connection, opts ...StuffClientOption) StuffClient {
    options := defaultStuffClientOptions
    for _, o := range opts {
        o(&options)
    }
    return &stuffClient{
        conn:    conn,
        timeout: options.Timeout,
        retries: options.Retries,
    }
}

We’ve defined now an additional unexposed variable containing our default options, and we’ve adjusted our constructor now to instead accept a variadic parameter. We then iterate over that list of StuffClientOption (singular) and for each of them, we apply the returned closure to our options variable (and recall that those closures accept an StuffClientOptions variable and simply modify the option value on it).

Now all we have to do to use it is this:

x := NewStuffClient(Connection{})
fmt.Println(x) // prints &{{} 2 3}
x = NewStuffClient(
    Connection{},
    WithRetries(1),
)
fmt.Println(x) // prints &{{} 2 1}
x = NewStuffClient(
    Connection{},
    WithRetries(1),
    WithTimeout(1),
)
fmt.Println(x) // prints &{{} 1 1}

That looks pretty nice and usable now. And the nice part about it is that we can very easily add new options any time we want with only a very minimal amount of change we need to make to the code.

Putting it all together we have something like this:

var defaultStuffClientOptions = StuffClientOptions{
    Retries: 3,
    Timeout: 2,
}
type StuffClientOption func(*StuffClientOptions)
type StuffClientOptions struct {
    Retries int //number of times to retry the request before giving up
    Timeout int //connection timeout in seconds
}
func WithRetries(r int) StuffClientOption {
    return func(o *StuffClientOptions) {
        o.Retries = r
    }
}
func WithTimeout(t int) StuffClientOption {
    return func(o *StuffClientOptions) {
        o.Timeout = t
    }
}
type StuffClient interface {
    DoStuff() error
}
type stuffClient struct {
    conn    Connection
    timeout int
    retries int
}
type Connection struct {}
func NewStuffClient(conn Connection, opts ...StuffClientOption) StuffClient {
    options := defaultStuffClientOptions
    for _, o := range opts {
        o(&options)
    }
        return &stuffClient{
            conn:    conn,
            timeout: options.Timeout,
            retries: options.Retries,
        }
}
func (c stuffClient) DoStuff() error {
    return nil
}

But this could be simplified even more by removing the StuffClientOptions struct and applying the options directly to our StuffClient.

var defaultStuffClient = stuffClient{
    retries: 3,
    timeout: 2,
}
type StuffClientOption func(*stuffClient)
func WithRetries(r int) StuffClientOption {
    return func(o *stuffClient) {
        o.retries = r
    }
}
func WithTimeout(t int) StuffClientOption {
    return func(o *stuffClient) {
        o.timeout = t
    }
}
type StuffClient interface {
    DoStuff() error
}
type stuffClient struct {
    conn    Connection
    timeout int
    retries int
}
type Connection struct{}
func NewStuffClient(conn Connection, opts ...StuffClientOption) StuffClient {
    client := defaultStuffClient
    for _, o := range opts {
        o(&client)
    }

    client.conn = conn
    return client
}
func (c stuffClient) DoStuff() error {
    return nil
}

Credit to Rob Pike and Dave Cheney for popularizing this design pattern.