I am an apologist of clean and readable code, therefore I find that a lot of arguments passed to functions usually do mean nothing, and people need to go through the functions to understand what they are doing and receiving.
Per example:
<?php
function hi($name, $age, $description) {
echo $name . ' - ' . $age . ' - ' . $description;
}
hi('John', 21, 'I\'m a builder');
?>
Should something like this be a better approach?
<?php
function hi($options) {
echo $options['name'] . ' - ' . $options['age'] . ' - ' . $options['description'];
}
hi(array(
'name' => 'John',
'age' => 21,
'description' => 'I\'m a builder'
));
?>
What is your opinion on this?
I agree with you that too many arguments are a code smell. Only not in the same way as you.
They are a code smell because it might mean the function / method is doing too much.
However if you do the latter you don't really fix anything. At least not what you are trying to fix:
and people need to go through the functions to understand what they are doing and receiving.
You second example does not fix this at all. It only makes it harder to understand what it does, because instead of being to able to look at the signature of the function now I really have to look at the body of the function to see what on earth the thing needs and does.
When I look at the signature of:
function hi($name, $age, $description)
it is clear the function expects a name, age and description. However when looking at the signature of:
function hi($options)
I will have no idea what it needs. $options
can be just about anything.
Another disadvantage of your second approach is that you have no way ever to add type hints to arguments.
Don't get me wrong. There are situations where it is perfectly fine to pass an entire array to a function, but I just don't feel this is one of them
What worries me more in your code is not the fact that there are three arguments, but rather that the function echo
s data directly instead of return
ing data. This makes it very inflexible.
Actually, PHP 5.6 just added new ways to pass arguments to functions!
http://php.net/manual/en/migration56.new-features.php#migration56.new-features.variadics
You can use the "..." operator to pass in an array of arguments.
The traditional option was to use your example and make sure you comment your code correctly.
Hope that helps!