开发者

Construtor with long parameter list OR multiple setters?

开发者 https://www.devze.com 2023-02-20 14:36 出处:网络
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 th

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消