Number of parameters for a constructor

ali_bahoo picture ali_bahoo · Jan 4, 2011 · Viewed 7.1k times · Source

I have a class that needs 12 parameters to be passed to its constructor. So I think that there is something wrong with the design of this class.

I would like to ask if there is any design pattern or a general collection of rules regarding the design of a class, especially its constructor.

Answer

Péter Török picture Péter Török · Jan 4, 2011

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.