Best way to pass values to a function when there are many to send?

岁酱吖の 提交于 2019-12-12 15:11:18

问题


What is the best way to define a method signature when you have to pass many values to a function and some of these may be optional. And in future, May be I have to pass more variables or subtract some passed values given to function.

For example: (phone and address are optional)

function addInfo( $name, $dob, $phone='', $address='' ) {
       // Store data
}

addInfo( 'username', '01-01-2000', '1111111' ); // address is not given

OR

function addInfo( $info ) {
    // Store data
}

$info = array( 'name'=>'username', 
               'dob'=>'01-01-2000', 
               'phone'=>'1111111', 
               'address'=>'' );
addInfo( $info );

回答1:


There's one more OOP-like way: create parameter object (for example, person) with fields 'name', 'dob', 'phone', 'address' (this is called Introduce Parameter Object refactoring in Fowler's "Refactoring" book). It seems appropriate in your case, since all fields you pass to function actually are related to one object.




回答2:


Martin suggests in "Clean Code", that you should limit the number of parameters atmost to 2-3 to keep the code easily understandable. So it would be better to wrap them into an object and pass the object as parameter. It's definitely preferable.




回答3:


Although the second version of the function seems better, it's not. That's because you don't know what kind of data the function expects. An array of elements is simply too generic. An object would fit better IMHO. A class object is well defined, where you expect eg. an Employee object and you call the function with an Employer, the call would fail.

So, to sum up, I would use either the first version or the class object way.




回答4:


I prefer the first version as it is more explicit and therefore more programmer friendly. A programmer can see at one glance what the function expects.

The second version would be preferred if the function could accept a large number of (optional) arguments. In that case it would make sense to bundle them and pass them as one unit.

I don't know about the performance implications to comment. I suspect that the penalty if any won't be severe.



来源:https://stackoverflow.com/questions/3744806/best-way-to-pass-values-to-a-function-when-there-are-many-to-send

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!