简体   繁体   English

练习在 Java 中使用长构造函数是否好?

[英]Is it a good to practice to have a long constructor in Java?

this is from a new to the domain!这是从一个新的域! thinking of an app to deal with an employee database in the university, an object employee should have at least 15 data points that need to be entered at object creation... is it normal to add all parameters in one constructor?考虑一个应用程序来处理大学里的员工数据库,一个对象员工应该至少有 15 个数据点需要在创建对象时输入......在一个构造函数中添加所有参数是否正常?

If no what are the alternatives?如果没有,有什么替代方案?

Item 2 of Effective Java, 3rd Edition (Bloch) is: Effective Java,第 3 版(Bloch)的第 2 项是:

Consider a builder when faced with many constructor parameters当面临许多构造函数参数时考虑构建器

However, the introductory sentence to the item clarifies a subtle point: constructors with many optional parameters are especially bad.但是,该项目的介绍性语句澄清了一个微妙的点:具有许多可选参数的构造函数尤其糟糕。

Static factories and constructors share a limitation: they do not scale well to large numbers of optional parameters.静态工厂和构造函数有一个限制:它们不能很好地扩展到大量可选参数。

In the text Bloch discusses two common alternatives to the Builder pattern:在文本中 Bloch 讨论了 Builder 模式的两种常见替代方案:

  • Telescoping constructor pattern (overloaded versions of the constructor with different configurations of the optional parameters);伸缩构造函数模式(具有不同可选参数配置的构造函数的重载版本);
  • The JavaBean pattern (parameterless constructor and setter methods). JavaBean 模式(无参数构造函数和 setter 方法)。

The long and short of it that the Builder pattern is preferred.总而言之,Builder 模式是首选。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM