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

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

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

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

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


当前回答

什么时候被认为如此淫秽的东西可以被监管,尽管第一修正案保证了言论自由?根据波特·斯图尔特法官的说法,“当我看到它的时候,我就知道了。”这里也是一样。

我讨厌制定这样的硬性规则,因为答案不仅取决于项目的大小和范围,而且我认为它甚至会改变到模块级别。这取决于你的方法在做什么,或者这个类应该表示什么,2个参数很可能太多了,这是过度耦合的症状。

我建议通过在第一时间提出这个问题,并尽可能多地限定你的问题,你真的知道所有这些。这里最好的解决方案不是依赖于一个硬性的数字,而是在同行中查看设计评审和代码评审,以确定低内聚性和紧密耦合的领域。

不要害怕向同事展示你的工作成果。如果您害怕,这可能是您的代码有问题的更大迹象,并且您已经知道了它。

其他回答

Alan Perlis著名的编程警句之一(在ACM SIGPLAN notice 17(9), 1982年9月中重新叙述)指出:“如果您有一个带有10个参数的过程,那么您可能错过了一些参数。”

根据我的说法,可能会有超过4个或某个固定数字的情况。 需要注意的事情可能是

你的方法做的太多了,你需要重构。 您可能需要考虑使用集合或某些数据结构。 重新考虑你的类设计,也许有些东西不需要传递。

从易于使用或易于阅读代码的角度来看,我认为当您需要对方法签名进行“换行”时,应该停下来思考,除非您感到无助,所有使签名更小的努力都没有结果。在过去和现在,一些非常好的图书馆使用超过4-5辆婴儿车。

根据亚马逊创始人杰夫·贝佐斯的说法,最多只能吃两个披萨:

非常感谢你的所有回答:

It was a bit surprising to find people who also think (like I do) that 5 parameters is a good limit for the sanity of the code. Generally, people tend to agree that a limit between 3 and 4 is good rule of thumb. This is reasonable as people usually have a bad time counting more than 4 things. As Milan points, on average people can keep more or less 7 things in their head at a time. But I think that you can't forget that, when you are designing/maintaining/studying a routine, you have to keep in mind more things than just the parameters. Some people consider that a routine should have as many arguments as it needs to. I agree, but only for a few specific cases (calls to OS APIs, routines where optimization is important, etc). I suggest to hide the complexity of these routines by adding a layer of abstraction just above these calls whenever possible. Nick has some interesting thoughts on this. If you don't want to read his comments, I summarize for you: in a nutshell, it depends: I hate making hard and fast rules like this because the answer changes not only depending on the size and scope of your project, but I think it changes even down to the module level. Depending on what your method is doing, or what the class is supposed to represent, it's quite possible that 2 arguments is too many and is a symptom of too much coupling. The moral here is don't be afraid of showing your code to your peers, discuss with them and try to "identify areas where you have low cohesion and tight coupling". Finally, I think wnoise much agrees with Nick, and concludes his satirical contribution with this poetical vision (see comments below) of the art of programming: Programming is not engineering. Organization of code is an art because it depends on human factors, which depend too much on context for any hard rule.

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

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