使用大量参数的缺点
我正在重写一些代码来进行功能更改,但我陷入了一种情况,要么我需要重载一个函数来容纳两种或三种类型的参数(但对它们执行几乎相同的操作),要么使用一个带有很多参数。现在我选择后一个选项,我只是想知道使用具有大量参数的函数的具体缺点(如果有的话)(当我说很多时,我的意思是 15 个)。
我正在寻找一个通用的答案,没有特定于语言的答案,所以我在这里不提及语言,只是为了提供信息,我正在使用 C#。
谢谢 仙人
I am re-writing some code to make functional changes and I am stuck at a situation where either I will need to overload a function to accommodate two or three types of parameters (but performing almost identical operations on them) OR use one function with a lot of parameters. Now I am going with the latter option, and I just wanted to know specific disadvantages (if any) of using a function with a lot of parameters (and when I say lot, I mean 15).
I am looking for a general answer, nothing language specific, so I am not mentioning the language here, but just for information, I am using C#.
Thanks
Rishi
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
大量参数的问题是,在调用代码的地方很难看出参数的含义:
某些语言通过允许命名参数和具有合理默认值的可选参数来解决这个问题。
另一种方法是将参数放入具有命名成员的参数对象中,然后将该单个对象作为参数传递给函数。这是一种名为 引入参数对象。
您可能还会发现将一组属于一个类的相关参数放入一个类中,将另一组参数放入另一个类中很有用。
The problem with a lot of parameters is that at the place where you call the code it can be difficult to see what the parameters mean:
Some languages solve this by allowing named parameters and optional parameters with sensible defaults.
Another approach is to put your parameters in a parameter object with named members and then pass that single object as the argument to your function. This is a refactoring appraoach called Introduce Parameter Object.
You may also find it useful to put one group of related parameters that belong together into one class, and another group of parameters into a different class.
您可以尝试以将要使用该方法的人的身份来思考。
最好的是对每个论点有一个可理解的使用。
如果并非在所有情况下都使用所有参数,您可以:
you may try to think as the one who will use the method.
The best is to have a comprehensible use of each arguments.
if all arguments are not used in all cases, you can :
如果您尝试“以函数式方式”编写代码,您可能会发现“Currying”有用,并创建仅使用几个参数初始化的有意义的函子对象。如果一个函数需要很多参数,它们的列表通常可以(或应该)被分成有意义的块,并且柯里化应该形成具有有意义意图的函数链。
因此,而不是(这个答案的示例):
你可能会使用
我不知道 C# 是否支持这个,但这就是函数式语言中通常解决问题的方式。
If you're trying to write your code "the functional way" you might find "Currying" useful, and create meaningful functor objects that are initialized with just a couple of parameters. If a function takes a lot of parameters, their list may (or should) usually be divided into meaningful chunks, and currying should form a chain of functions with meaningful intent.
So instead of (example of this answer):
you might use
I don't know if C# supports this, but that's how the problem is usually solved in functional languages.
我通常处理这个问题的方法是为每个所需的签名提供非常小的单独方法,但让它们调用私有方法来完成实际工作,正如您所说,这在用例之间几乎是相同的。
The way I normally handle this is to have very small separate methods for each signature needed, but have them call private methods to do the actual work, which as you said is pretty much identical between the use cases.