0

It's about code readability:

I've been dealing with this for a long time and I always wonder what would be the best approach to deal with passing parameters.

Lots of times, reading code from other programmers I find lines as such:

$Instance->functionCall('Abc123', 5, 1.24, 'XYZ', 642);

This makes me have to go to the Class file and take a look at what those parameters mean.

I do my best to write readable code by doing this:

$user_name = 'Abc123';
$age = 5;
$height = 1.24;
$hobbies = 'XYZ';
$num_brothers = 642;

$Instance->functionCall($user_name, $age, $height, $hobbies, $num_brothers);

Or this:

$Instance->functionCall($user_name = 'Abc123', $age = 5, $height = 1.24, $hobbies = 'XYZ', $num_brothers = 642);

But this variables occupies memory, not being used anywhere else. I like to think that this 'lost' memory space is worth it by being more readable, but I'd like to know if there is a better way.

Any ideas?

Thanks all!

Didhack
  • 58
  • 8
  • Use first approach with phpdoc (documentation to your methods and variables) and you are good to go - your IDE will tell you what you need to know – m_pro_m Sep 15 '15 at 14:21

2 Answers2

1

What about something like this:

$Instance->functionCall([         // or $Instance->functionCall( array(
    'user_name'    => 'Abc123',
    'age'          => 5,
    'height'       => 1.24,
    'hobbies'      => 'XYZ',
    'num_brothers' => 642
]);

pass an array into the function. That way you have the readability of individual variables and can easily add more/less to the function as needed.

Adunahay
  • 1,551
  • 1
  • 13
  • 20
  • I like this, in fact I've used it some times. I think is a good approach, but when I use it I ask myself "where's the line between passing parameters individually or an array containing all of them? Passing only one int justifies using an array to contain it? If not, passing also a string does?". Moreover, you lose the functionality of default parameter values. – Didhack Sep 15 '15 at 14:30
0

First of all functions can have many parameters only in extreme cases, but usually if you have a lot of them - refactor. In given case it looks like there should be some User object that has to be passed to the function only and you can get all required data from that object inside the function. And also use PHPDoc, as @m_pro_m said your IDE will tell you what you need.

Also this practise

$Instance->functionCall('Abc123', 5, 1.24, 'XYZ', 642);

Is bad because of so called "magic numbers and strings". If you find such things, export them to a constant or some config.

Community
  • 1
  • 1
unxp
  • 318
  • 2
  • 12