Srinivas Kandukuri
Posted on December 13, 2022
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
}
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,
}
}
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)
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
}
}
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
}
Client creates basic Config
appConfig := NewConfig("http://api.google.com")
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))
Resources:
Posted on December 13, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.