views:

53

answers:

4

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

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.

Manoj Govindan
+3  A: 

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.

Kel
http://sourcemaking.com/refactoring/introduce-parameter-object, http://www.refactoring.com/catalog/introduceParameterObject.html
Archimedix
+4  A: 

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.

Ravi Gummadi
+1  A: 

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.

Vasileios Lourdas