Saturday, May 24, 2025
HomeGolangThe best way to deal with flow-style interface of embedded kind -...

The best way to deal with flow-style interface of embedded kind – Getting Assist


Assume I’ve a third-party kind that implements a flow-style interface, i.e. calling a operate on a pointer operate replace the state and returns the pointer again:

kind ThirdPartyType struct {}

func NewThirdPartyType() *ThirdPartyType {
    return &ThirdPartyType{}
}

func (tpt *ThirdPartyType) Foo(foo string) *ThirdPartyType {
    // ...
    return tpt
}

Utilizing such a kind is succinct:

tpt := NewThirdPartyType().Foo("foo")

I need to wrap this ThirdPartyType and add just a few new strategies. For this I embed it into MyType like

kind MyType struct {
    *ThirdPartyType
}

func NewMyType() *MyType {
    return &MyType{}
}

func (mt *MyType) Bar(bar string) *MyType {
    // ...
    return mt
}

Whereas for my customized strategies I can retain the circulate model, I can not for those “inherited” by ThirdPartyType as they return *ThirdPartyType and thus can’t be used within the chain:

var mt *MyType = NewMyType().Bar("bar")
mt.Foo("foo")

That is quite unlucky because it defeats the succinctness I had earlier than. The one resolution I discovered to date is to re-implement the strategies of ThirdPartyType on MyType like:

func (mt *MyType) Foo(foo string) *MyType {
    mt.Foo(foo)
    return mt
}

Now I can actually do

mt := NewMyType().Bar("bar").Foo("foo")

Nevertheless, that is fairly a little bit of boilerplate. Plus, the variety of strategies I’d must re-implement is round 50, so I’d quite not keep this by hand.

The very best resolution I got here up with is to make use of code era coupled with replicate to deal with this robotically. I simply need to test if I’m lacking an easier resolution earlier than I am going down this route.

Hey there. Sadly, so far as I do know there is no such thing as a resolution for this query. Digging deeper I suppose it’s additionally extra about design of the implementation. Specifically, I don’t like strategies chaining and attempt to keep away from it in go as a lot as doable and favor the useful choices sample. In case you wanna persist with the chaining, I’d advise to checkout gorm supply code. I’ve by no means seen something higher with chaining, than this bundle

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments