vendredi 3 novembre 2023

Composition For WithOptions Pattern in Golang

In golang there's a pretty cool pattern for variadic options as

CallSomeStaff(mandatoryArg, WithSomeVariadicOption(val1), WithOtherVariadicOption(val2))

But what is the best/intended practice (or at least appropriate solution) once we want to extend the logic with any supper function which might add its own variadic options.

It seems tricky as

  • The type of the options it self are not always exposed, just the Option Modifiers
  • I'm not really sure, but it seams to me there. was a case when event a type of the Options Modifiers where privates instead just a final Modifier Function Values were exposed

So is it really possible to smoothly implement something like

func SupperWrapper(composedOptions ...SuperOrInheritedOptions) {
   superOptions := // filter for SuperOptions
   inheritedOptions := // filter for InheritedOptions

   doWhateverWith(superOptions)

   CallSomeWrappedStaff(...inheritedOptions)
}

The interface{} approach as an options type looks too spooky.

The most pretty stuff I can see that is possible to implement would look something like

SuperStaff(
  WithSupperOption1(), 
  WithSuperOption2(), 
  WithInheritedOptions(
    WithInheritedOption1(), 
    WithInheritedOption2(),
 ),
)

Any way is it possible really to end up with plain mix of options as

SuperStaff(
  WithSupperOption1(), 
  WithSuperOption2(), 
  WithInheritedOption1(), 
  WithInheritedOption2(),
)

And the Supper Question is what are really the option to go once the original types are not exposed for the options it self or even the modifiers types as well.

P.S. As I understand (as the simplest solution) a type composition like

type CompositeOptions = SuperOptions | InheritedOptions

is not supported in golang. Isn't it?

Thx

Aucun commentaire:

Enregistrer un commentaire