optional parameter in function

https://blog.detectify.com/2019/09/05/how-we-tracked-down-a-memory-leak-in-one-of-our-go-microservices/



https://blog.yongweilun.me/go-generics-draft-design-final



https://github.com/lucasepe/modgv



https://www.pixelstech.net/article/1600482330-One-good-way-to-use-optional-parameter-in-function



n GoLang, it doesn’t support method overloading like in Java, hence sometimes it would be a headache to create functions to construct new structs with different parameters.



Normally, we would construct the new function as below when want to let others create a new struct instance with explicit function call.



type Queue struct {
Name string
}



func NewQueue(name string) *Queue {
return &Queue{name}
}
But with the scope and complexity of the struct increases, there might be more properties added to Queue.



type Queue struct {
Name string
MaxLimit int
}
How to enhance the NewQueue() to accomodate the new property? One might have below ideas:



func NewQueue(name string, maxLimit int) *Queue – this breaks backward compatibility
func NewQueueWithLimit(name string, maxLimit int) *Queue – each new property will have a new function with some name like above and lots of permutations are needed if properties are increasing
func NewQueue(config *QueueConfig) *Queue – this is also breaking backward compatibility and also it’s difficult to handle default value

Is there a better option? Yes, option pattern can be used to handle such cases. Basically the key here is to utilize the variadic function.



type Queue struct {
Name string
MaxLimit int



// monitor
MonitorInterval int }


type QueueOption func(*Queue)



func WithMaxLimit(max int) QueueOption {
return func(q *Queue) {
q.MaxLimit = max
}
}



func WithMonitorInterval(seconds int) QueueOption {
return func(q *Queue) {
q.MonitorInterval = seconds
}
}



func NewQueue(name string, options …QueueOption) *Queue {
queue := &Queue{name, 10, 5}



for _, o := range options {
o(queue)
}

return queue } With this pattern, it is not breaking the backward compatibility and also any number of optional parameter can be added with only need of WithXXX() function added. This pattern is similar to decorator pattern in Java and other OOP languages.


The drawback is that a new WithXXX() function is needed whenever a new parameter is added. But this cost is small compare to other solutions available. Also please balance it as it’s not needed if the foreseeable parameters for a struct would not be that too many and not many of them should be configurable.



Reference: https://jiajunhuang.com/articles/2020_04_20-golang_optional_parameters.md.html


Category golang