mercredi 3 août 2022

Simplifying a trait method with too many arguments?

I have a trait, which defines several functions. One of these functions has too many arguments. It also is a default implementation and inside, it makes calls to other trait functions via self. My question is how do I reduce the number of arguments to the function without going into massive refactoring?

My first instinct was to go with a builder pattern. I would define a new struct that would contain all the arguments to the function. With this, I would modify the default trait implementation to instead return a builder object and then have the user supply the arguments to the builder. Finally, the actual implementation code would then go in to some .build() or execute function.

The problem with that approach is that the default implementation uses self. This means that I need to have the build function take the trait as an argument, something like fn build(&self, &impl MyTrait) -> Result<>. I don't like this because this is kinda ugly:

let res = something.handle()
              .withArg1(...)
              .withArg2(...)
              .build(something);

What better ways can I simplify this?

Aucun commentaire:

Enregistrer un commentaire