javaconstructorlong-parameter-list

Construtor with long parameter list OR multiple setters?


To initialize an instance, we can use either a default constuctor and a number of setters, or a constructor with a long parameter list. In the latter way the object state may remain unchanged after the object is generated(because there is not setter), but a long parameter list is ugly and error-prone. In the former way the long parameter list is avoid, but the object state may be changed by setters by mistake after the object has been completely created.

I need such an object that its internal fields should remain unchanged after the object is created, while I do not like long parameter list. What is the best practice to do it?


Solution

  • Use Builder pattern:

    Foo foo = new FooBuilder().setBar(...).setBaz(...).build();