Java中构造函数中的长参数列表 [英] Long parameter list in constructor in Java
问题描述
如果一个构造函数有一个长参数列表,我们应该考虑它的风格和重构吗?如果是,如何?
If a constructor has a long parameter list, should we consider it bad style and refactor it? If yes, how?
推荐答案
这可能是一组适当的参数,但很多时候我的答案是yes 。将参数分成逻辑子组,如果它们存在的话,而不是从许多不同的部分创建一个汽车,将一些部分组成一个Engine对象,一些进入Chasis等。
It may be an appropriate set of parameters, but a lot of the time my answer would be yes. Break the parameters into a logical subgroupings if they exist i.e. rather than creating a Car from many different parts, group some parts into an Engine object, some into a Chasis etc.
或者,如果某些参数是可选的,请使用构建器模式,以便在必要时只包括它们。
Alternatively, if some of those parameters are optional, make use of the builder pattern so that you only include them when necessary.
最后,您和您的网域。
这篇关于Java中构造函数中的长参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!