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

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

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

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

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


当前回答

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

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

其他回答

我同意3个是可以的,4个太多了。如果有3个以上的参数,你就不可避免地要做不止一个任务。一个以上的任务应该被分割成不同的方法。

然而,如果我查看我所从事的最新项目,例外情况比比皆是,大多数情况下很难归结为3个参数。

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

非常感谢你的所有回答:

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.

作为一般的经验法则,我停留在三个参数上。如果再多,就应该传递一个参数数组或配置对象,这也允许在不更改API的情况下添加未来的参数。

我的答案将基于函数被调用的频率。

如果它是一个只被调用一次的init函数,那么就让它占用10个parms或更多,谁在乎呢。

如果它每帧被调用一堆次,那么我倾向于创建一个结构,并只传递一个指针给它,因为这往往更快(假设你不是每次都重建结构)。