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

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

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

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

我的问题是,什么时候我可以认为一个参数列表太大?我认为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.

这个答案假设使用面向对象语言。如果你不使用,跳过这个答案(换句话说,这不是一个语言不可知的答案。

如果你传递了超过3个左右的参数(特别是内在类型/对象),这并不是“太多”,而是你可能错过了创建一个新对象的机会。

寻找传递给多个方法的参数组——即使是传递给两个方法的参数组也几乎可以保证在那里有一个新对象。

然后,您将功能重构到新对象中,您无法相信它对代码和对OO编程的理解有多大帮助。

我认为实际的数字取决于函数上下文的逻辑意义。我同意大约4-5个参数开始变得拥挤。

在设置标志的情况下,处理这种情况的一个好方法是枚举值并将它们一起OR。

如果我在一个例程中有7-10个参数,我会考虑将它们捆绑到一个新类中,但如果这个类只是一堆带有getter和setter的字段,那么这个新类必须做一些其他的事情,而不是将值移进和移出。否则,我宁愿忍受很长的参数列表。

我想说,只要你有2-4的过载,如果你需要的话,你就可以去更高的地方。