mardi 10 octobre 2023

Instantiate several children with similar arguments

I have the class Base, and the classes A, B, C, D, ... that extend this class. Base has a constructor with too many parameters (bad practice, but I can't change that). Most of the children classes have only these parameters, but some children classes can have 1 or 2 more arguments. Something like this:

class Base {
   private readonly string _arg1;
   private readonly string _arg2;
   (...)

   public Base(string arg1, string arg2, string arg3, ..., string arg_n) {
       _arg1 = arg1
       _arg2 = arg2
      (...)
   }
}

class A : Base {
   public A(string arg1, string arg2, string arg3, ..., string arg_n) : 
       base(arg1, arg2, arg3, ..., arg_n)
   }
}

class B : Base {
   private readonly string _arg_m;

   public B(string arg1, string arg2, string arg3, ..., string arg_n, string arg_m) : 
       base(arg1, arg2, arg3, ..., arg_n)
       _arg_m = arg_m;
   }
}
etc...

I want to instantiate one element of each class, using the same instances for the arguments. Something like:

var arg1 = "something";
(...)
var arg_n = "something";

var a = new A(arg1, arg2, arg3, ... , arg_n);
var b = new B(arg1, arg2, arg3, ... , arg_n, "foo");
(...)

I would like to do it without repeating the code too much. I though I could create a factory:

class Factory {
    Factory(string arg1, string arg2, string arg3, ..., string arg_n) {
       (...)
    }

and then reuse these parameters. My original code would be simplified to

var arg1 = "something";
(...)
var arg_n = "something";
var factory = new Factory(arg1, arg2, arg3, ... , arg_n);

var a = factory.GetA();
var b = factory.GetB("foo");
(...)

but then the factory would contain all the new A(list of arguemnts) for all the children. So, basically, I'm not reducing code but moving it.

Is there a pattern to create all these children without so much verbosity? Thanks.

Aucun commentaire:

Enregistrer un commentaire