I have dilemma on the format of method parameters for a function in PHP (could be any language). The following are the two candidates
Candidate 1:
function foo($param1,$param2,$param3,....$paramN)
and
Candidate 2:
function foo ($arr) {
$param1 = $arr['param1'];
$param2 = $arr['param2'];
$param3 = $arr['param1'];
...
...
...
$paramN = $arr['paramN'];
}
I am leaning towards candidate 2 at the moment because I have couple of methods which have many parameters. But, I am also concerned that if I go on the path of Candidate 2, then my code has the risk to become unreadable and not easily maintainable. While Candidate 2 is also very enticing because now the order of the params becomes irrelevant (hence the method signature) but I am afraid debugging would become a pain in the butt.
So which is the recommended way? Which candidate to choose and why?
Lots of parameters are never nice to handle, I would personally opt for candidate 2 because it is more extensible. You can compensate for the “mess” with a validation logic that ensures, that all required parameters are set correctly.
The – in my opinion – best way is to refactor your code and split the method in several, maybe chainable parts so the complexity is reduced.
What might also be a nice option is to use Value Objects (or sometimes also Data Transfer Objects), to pass all the parameters in a sort of “container”. In this way, it’s ensured that only valid data can be passed, because the Value Object iself cares for its contents.