samedi 18 janvier 2020

Differences between the immutable setter and traditional setter while set up an Option object

After a time of investigating open source projects, I often see the pattern in the setting options for a class. (Let say "immutable method")

// list of possible options
type Options struct {
    Sampler sampler
    SpanKind int
}

// define an apply function. which will be called when really initialize an object
type Option func(*Options)

// for each option. Return an function to apply that specific option
func WithSpanKind(spanKind int) Option {
    return func(o *Options) {
        o.SpanKind = spanKind
    }
}

// then. we we build a new object, we just need to receive a list of option
func NewObject(options ...Option) Object {
}

Comparing to the above method, there is another way that using simple getter/setter.

func (o *Options) SetSpanKind(kind int) {
   o.spanKind = kind
}

// then. we we build a new object by using directly the Options object
func NewObject(option Options) Object {
}

My question is: What are the differences between those approaches and why the first approach always prefers in many open sources that I have read.

Noted: Here are some open sources with the line that implements the above pattern. Those open sources are initiated by Google, so maybe this pattern only specific to only Google, though.

Thanks

Aucun commentaire:

Enregistrer un commentaire