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

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

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

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

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


当前回答

多了一个。我并不是说要油嘴滑舌,但是有些函数确实需要一些选项。例如:

void *
mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t offset);

有6个论点,每一个都是必不可少的。此外,它们之间没有共同的联系来证明捆绑销售是合理的。也许你可以定义“struct mapargs”,但那更糟糕。

其他回答

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.

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

多了一个。我并不是说要油嘴滑舌,但是有些函数确实需要一些选项。例如:

void *
mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t offset);

有6个论点,每一个都是必不可少的。此外,它们之间没有共同的联系来证明捆绑销售是合理的。也许你可以定义“struct mapargs”,但那更糟糕。

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

97听起来差不多。

少了一点,你就失去了灵活性。