Search code examples
oopdesign-patternsbuilder-pattern

Is the builder pattern suitable for the same representation/output but a slightly different process?


My API has different parameters. Depending on those, I have two slightly different processes. But output almost same. Should I use builders pattern ?

For example, suppose there are different query parameters A and B:

// For case A: 
if (A){
  funX(A);
  funY();
  funZ();
}

// For case B :
if(B){
  funW(B);
  funX(B);
  funY();
  funZ();
}

Note : here process is little bit complex. Such as Third party api call, filter, sorting, complex calculation and so on.


Solution

  • The simple fact of having slightly different processes does not justify nor call for a builder pattern.

    Unfortunately, your question doesn't show anything about your object structure, so it's difficult to advise how to implement it. Typically, here some examples:

    • polymorphism: different classes implement the behavior promised in their base class a little bit differently. Depending on your parameters, you would instantiate the right class.
    • template method is a particular use of polymorphism, where the core structure of the process is implemented in the base class, and make use of auxiliary functions that are implemented slightly differently.
    • composition: parts of the behavior are implemented in different classes/objecs. the process is can be assembled by composing the different parts. It is more flexible than inheritance.
    • strategy, decorator, command, chain of responsibility are all design patterns that use composition (sometimes in relation with inheritance), that could allow to implement the behavior slightly (or radically) differently. Plenty of other approaches use composition to achieve your goals.

    Anyway, try not to use design patterns as a catalogue of basic ingredients to solve your problem. THe right way is the opposite: think of how you want to solve the problem, and then use design patterns if you see that they address some of your desing intentions.

    To come back on the builder pattern: this is a pattern that is meant to construct complex classes, and apply a same construction process to different classes that follow a same logic for their construction. I don't see this kind of challenge in your code example.