Java constructor with large arguments or Java bean getter/setter approach

后端 未结 18 2156
清歌不尽
清歌不尽 2020-12-12 21:29

I can\'t decide which approach is better for creating objects with a large number of fields (10+) (all mandatory) the constructor approach of the getter/setter. Constructor

18条回答
  •  一生所求
    2020-12-12 22:13

    The better approach (imho) is to use some kind of builder:

    MyClass a = new MyClassBuilder().blah("blah").foo("foo").doStuff().toMyClass();
    

    where MyClass is still immutable but has a far more readable creation than a constructor with 10 arguments.

    This is also called a fluent interface. Josh Bloch refers to this in Effective Java.

提交回复
热议问题