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?
Use Builder pattern:
Foo foo = new FooBuilder().setBar(...).setBaz(...).build();
A long parameter list could (but doesn't have to) mean that the class should be refactored to smaller classes.
精彩评论