DEV Community

Cover image for Options Pattern in Golang
Srinivas Kandukuri
Srinivas Kandukuri

Posted on

Options Pattern in Golang

What ..?

Option pattern very powerful in terms of modify the behaviour of the function without changing the code.
It is a function programming pattern that is used to provide optional arguments to a function.

example when user want to pass additional parameter to a function in SDK, then it modifies the behaviour accordingly.

suppose we have struct name called config which contains below configs

type Config struct{
        url     string
        port    string
        timeout time.Duration
    }
Enter fullscreen mode Exit fullscreen mode

and now our factory methods something like this.

func NewConfig(url string,port string, timout time.Duration) *Config{
    return &Config{
        port:port,
        url:url,
        timeout:timeout,            
    }       
}
Enter fullscreen mode Exit fullscreen mode

But i want port and timeout to be optional parameters. only url i want to make it mandatory

let's define new type called Option

type Option func(*Config)
Enter fullscreen mode Exit fullscreen mode

Option is a function that takes Config . By using this option will modify the Config

func WithPort(port string) Option{
    return func(c *Config){
        c.port = port
    }
}

func WithTimeout(timeout time.Duration) Option{
    return func(c *Config){
        c.timeout = timeout
    }
}
Enter fullscreen mode Exit fullscreen mode

Option is just a function it takes the pointer and return the updated config. now we have set the desired values to our config. Let's update the Factory method

func NewConfig(url string, opts ...Option) *Config{
    config := &Config{
        url:url
    }
    for _, opt := range opts{
        opt(config)
    }
    return config
}
Enter fullscreen mode Exit fullscreen mode

Client creates basic Config

appConfig := NewConfig("http://api.google.com")
Enter fullscreen mode Exit fullscreen mode

Client creates url with port

appConfig := NewConfig("http://api.google.com", WithPort("3000"))
appConfig := NewConfig("http://api.google.com", WithPort("3000"), WithTimeout(30*time.Second))
Enter fullscreen mode Exit fullscreen mode




Resources:

Top comments (0)