开发者

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

开发者 https://www.devze.com 2023-01-17 04:47 出处:网络
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 som

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 );


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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消