2

I have dilemma on the format of method parameters for a function in PHP (could be any language). The following are the two candidates

Candidate 1:


function foo($param1,$param2,$param3,....$paramN) 

and

Candidate 2:


function foo ($arr) {
   $param1 = $arr['param1'];
   $param2 = $arr['param2'];
   $param3 = $arr['param1'];
   ...
   ...
   ...
   $paramN = $arr['paramN'];
}

I am leaning towards candidate 2 at the moment because I have couple of methods which have many parameters. But, I am also concerned that if I go on the path of Candidate 2, then my code has the risk to become unreadable and not easily maintainable. While Candidate 2 is also very enticing because now the order of the params becomes irrelevant (hence the method signature) but I am afraid debugging would become a pain in the butt.

So which is the recommended way? Which candidate to choose and why?

4

1 回答 1

3

很多参数都不好处理,我个人会选择候选 2,因为它更具可扩展性。您可以使用验证逻辑来​​弥补“混乱”,以确保正确设置所有必需的参数。

- 在我看来 - 最好的方法是重构您的代码并将方法拆分为几个可能是可链接的部分,从而降低复杂性。

也可能是一个不错的选择是使用值对象(或有时也使用数据传输对象),以一种“容器”的形式传递所有参数。通过这种方式,可以确保只能传递有效数据,因为值对象本身关心其内容。

于 2012-11-11T20:31:59.953 回答