Builder/Factory Pattern – Applicability to Design Problems

architectural-patternsdesign-patterns

I have the following code and I am not sure if the builder factory is the best approach to solve this code duplication.

createA(a, b, c, e: {e1, e2}){
    return{
    a
    b
    c
    e
    }
}

createB(a, b, e: {e1, e2, e3}){
    return{
    a
    b
    e
    }
}

createC(a, e: {e1, {ee1, ee2}, e3}){
    return{
    a
    b
    e.ee1
    e.ee2
    {e1, e2}
    }
}

The problem here is that there are some params that are used in each function but not others. This is only an example. The real functions have a lot, so I prefer not to use optional params, and as you can see with these params build a JSON object that in general is almost the same between these functions.

I thought to create one class and set the common parameters in the constructor and the rest in a lot of functions like createA (b, c, e: {e1, e2}) and get the common params from the constructor, but probably another pattern is more common or expected, so what are your recommendations for this?

EDIT

Finnaly I used the following code:

class builderJson{

   private a

   constructor(a){
       this.a = a
   }

   private buildBase(params){
       return {a, params}
   }

   public buildA(b,c,e){
       return this.buildBase(b,c,e)
   }

   ...

}

Kind regards.

Best Answer

The builder pattern involves different types for the builder vs. what will eventually be constructed.  While the purpose of the builder pattern is to support complex construction, let's note that the builder pattern uses the type system to prevent the program from seeing uncompleted instances of the intended eventual type.  When the intended object is finally created, it is fully functional and ready to be used — it could even be immutable.

What you are suggesting is to use the constructor to build an unfinished object and then finish it later, which is a more error prone protocol, since the caller could fail to invoke the finishing methods without message from the compiler.  Such objects also cannot be immutable, since they must be modified after construction.