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

后端 未结 18 2149
清歌不尽
清歌不尽 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:26

    If all parameters are in fact mandatory, then I see no reason why not to use a constructor. However, if that's not the case, then using a builder seems like the best approach.
    Relying only on setters is in my opinion the worst solutions since there's nothing to enforce that all mandatory properties are set. Of course if you're using Spring Framework's bean wiring or other similar solution, then Java beans are perfectly fine as you can check after the initialization that everything has been set.

提交回复
热议问题