使用大量参数的缺点 [英] Disadvantages of using a lot of parameters

查看:150
本文介绍了使用大量参数的缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重写一些代码以进行功能更改,并且我陷入了一种情况,即需要重载一个函数以容纳两种或三种类型的参数(但对其执行几乎相同的操作),或者使用一种函数有很多参数。现在我选择后一种选择,我只想知道使用具有很多参数的函数的具体缺点(如果有的话)(当我说很多时,我的意思是15)。

我正在寻找一个通用的答案,没有任何语言特定的,所以我不提这里的语言,但只是为了获取信息,我正在使用C#。



感谢
Rishi

解决方案

很多参数是在您调用代码的地方,可能很难看出参数的含义:

  //呃......什么? 
run(x,y,max_x,true,false,dx * 2,range_start,range_end,0.01,true);

有些语言通过允许命名参数和可选参数以合理的默认值解决了这个问题。



另一种方法是将参数放在带有名称成员的参数对象中,然后将该单个对象作为参数传递给函数。这是一个重构的appraoach,名为介绍参数对象



您也可能发现将一组属于一组的相关参数合并到一个类中是有用的,参数转换为不同的类。


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

解决方案

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:

// Uhh... what?
run(x, y, max_x, true, false, dx * 2, range_start, range_end, 0.01, true);

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.

这篇关于使用大量参数的缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆