In general, what is the maximum number of parameters a class constructor should accept? I’m developing a class that requires a lot of initialization data (currently 10 parameters). However, a constructor with 10 parameters doesn’t feel right. That leads me to believe I should create a getter/setter for each piece of data. Unfortunately, the getter/setter pattern doesn’t force the user to enter the data and without it characterization of the object is incomplete and therefore useless. Thoughts?
In general, what is the maximum number of parameters a class constructor should accept?
Share
With that many parameters, it’s time to consider the Builder pattern. Create a builder class which contains all of those getters and setters, with a build() method that returns an object of the class that you’re really trying to construct.
Example:
And in your client code:
See pages 7-9 of Effective Java Reloaded [pdf], Josh Bloch’s presentation at JavaOne 2007. (This is also item 2 in Effective Java 2nd Edition, but I don’t have it handy so I can’t quote from it.)