I'm writing a utility function to handle arrays. For the sake of avoiding complexity let's say it's a simple handle to allow shorthand array insertion into a function:
function array_insert($original_arr,$key,$val){
$original_arr[$key]=$val;
return $original_arr;
}
With the use case being e.g.
validate_input(array_insert($_GET,'extra-key','val'));
Now let's say we could have the issue that $_GET
might not be an array. Or say we're taking input from an external call; where does the responsibility lie in checking that the first parameter is an array?
If this formed the start of a complex stack of processing we could do:
if (is_array($our_data)){
do_something($our_data);
do_something_else(array_insert($our_data,'key','val'));
}
This doesn't have the effect of letting the calling scope know that do_something
didn't happen though. So we could do:
if (!is_array($our_data)){
throw new Exception('not an array');
}
Now anything using our method needs to be prepared to catch that, and depending on whether we actually care about the result we might need to catch it within our method.
We could simply get out of the utility function and return false which something else can check for:
function array_insert($original_arr,$key,$val){
if (!is_array($our_data)){
return []; // which is empty but expected, or return false.. or null...
}
}
Then there's the lowest level:
function array_insert(Array $original_arr)
Which will trigger a PHP level exception if an array isn't passed.
So the question is; for a utility function how much responsibility do we take about use case? Do we cause a language exception with a TypeHint, do we fail silently, do we not bother to check and let the end user figure it out?
Update
Firstly people are noting that this is subjective - I agree, though there is likely to be an established best practice, e.g. one recommended by certification schemes or large companies in the PHP world.
Secondly a further question (prompted by the first answer) is if there's an established Exception class/class name for this kind of issue?