One good way to use optional parameter in function

  sonic0002        2020-09-18 21:45:29       10,154        0    

In 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

OPTION PATTERN  VARIADIC FUNCTION  OPTIONAL PARAMETER 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

Spent whole life on compiling