例程可以有参数,这不是新闻。您可以根据需要定义任意多的参数,但是过多的参数会使您的例程难以理解和维护。

当然,您可以使用结构化变量作为解决方法:将所有这些变量放在单个结构中并将其传递给例程。事实上,使用结构来简化参数列表是Steve McConnell在Code Complete中描述的技术之一。但正如他所说:

谨慎的程序员避免将数据捆绑在一起,除非逻辑上是必要的。

因此,如果你的例程有太多的参数,或者你使用一个结构体来掩盖一个大的参数列表,你可能做错了什么。也就是说,你没有保持耦合松散。

我的问题是,什么时候我可以认为一个参数列表太大?我认为5个以上的参数太多了。你怎么看?


当前回答

A length restriction on a parameter list is just one more restriction. And restriction means applied violence. It sounds funny, but you can be non-violent even when programming. Just let the code dictate the rules. It is obvious that if you have many parameters, the body of the function/class method will be big enough to make use of them. And big code snippets usually can be refactored and split into smaller chunks. So you get solution against having many parameters as free bonus, since they are split among the smaller refactored pieces of code.

其他回答

如果您开始在心里计算签名中的参数,并将它们与调用匹配,那么是时候重构了!

众所周知,人们平均一次能记住7 +/- 2件事。我喜欢把这个原则用在参数上。假设程序员都是智商高于平均水平的人,我会说任何10+都太多了。

顺便说一句,如果参数在任何方面相似,我会把它们放在向量或列表中,而不是结构体或类中。

我自己把公共函数的极限画在5个参数上。

恕我直言,长参数列表只适用于私有/本地helper函数,这些函数只能从代码中的几个特定位置调用。在这些情况下,您可能需要传递大量的状态信息,但可读性并不是一个大问题,因为只有您(或维护您的代码并应该了解模块基础的人)必须关心调用该函数。

A length restriction on a parameter list is just one more restriction. And restriction means applied violence. It sounds funny, but you can be non-violent even when programming. Just let the code dictate the rules. It is obvious that if you have many parameters, the body of the function/class method will be big enough to make use of them. And big code snippets usually can be refactored and split into smaller chunks. So you get solution against having many parameters as free bonus, since they are split among the smaller refactored pieces of code.

您应该考虑的一个相关问题是例程的内聚性如何。大量参数可能是一种气味,告诉您例程本身试图做太多事情,因此它的内聚性是可疑的。我同意一个固定的参数数量可能是不可能的,但我猜一个高内聚例程意味着一个低数量的参数。