Number of parameters for a constructor

12 parameters definitely sound too many to me. Options to reduce their numbers are:

  1. Introduce Parameter Object by grouping logically related parameters into an object and passing that object instead of the individual parameters.

  2. Introduce a Builder (optionally with method chaining). This does not reduce the actual parameter list but it makes the code more readable, and is especially useful if you have several different creation scenarios with varying parameters. So instead of

    MyClass someObject = new MyClass(aFoo, aBar, aBlah, aBaz, aBorp, aFlirp, 
            andAGoo);
    MyClass anotherObject = new MyClass(aFoo, null, null, aBaz, null, null, 
            andAGoo);
    

    you can have

    MyClass someObject = new MyClassBuilder().withFoo(aFoo).withBar(aBar)
            .withBlah(aBlah).withBaz(aBaz).withBorp(aBorp).withFlirp(aFlirp)
            .withGoo(aGoo).build();
    MyClass anotherObject = new MyClassBuilder().withFoo(aFoo).withBaz(aBaz)
            .withGoo(aGoo).build();
    
  3. (Maybe I should have started with this 😉 Analyse the parameters – Are all of them really needed in the constructor (i.e. mandatory)? If a parameter is optional, you may set it via its regular setter instead of the constructor.

Leave a Comment