I have a small function that returns the value that has the highest priority, which for now is not defined anywhere, just because of the order in which I evaluate the values:
public function obtenerValorMasImportante($datos = null) {
if ($datos->getDato1()) {
return 'dato1';
}
if ($datos->getDatoX()) {
return 'datox';
}
if ($datos->getLoQueSea()) {
return 'loquesea';
}
if ($datos->getOtraCosa()) {
return 'otracosa';
}
return false;
}
The problem is simple: the code works, but what if I have 100 values? I would have to write 100 if
and it is not a good idea, I am not flowing with ideas at this time of day either.
I have no further control over the object $datos
, so modifying it or adding information to it is not an option.
How could I reduce the number of if? or failing that, make the code independent of the number of values.
It's not that
eval
it's "bad", another downside is that you can't easily catch errors , and the code is not portable to PHP 7, as you must include a statementreturn
or it will return NULL.Also, you don't need to use
eval
. You can dynamically call a method withcall_user_func
.Although in the example the method name and the return value are one less 'get' in the chain and returning
strtolower($nombre_metodo)
, suppose this is not the case, and that we have to map called method names to disparate values:If the values are always equal to
strtolower($metodo)
the array it can be simpler, like Álvaro's example, but again, there is no need to use eval. Always prefer call_user_funcSince all conditionals have the same basic structure, this is one case where you might use
eval
. The idea would be that you change the function to do something like this:eval
assigns the value of the getter to an auxiliary variableThe code would be like this:
So now the only thing you have to maintain is the list of attributes ordered by priority.
Yes, I know there will be people who will say " but
eval
it's diabolical and shouldn't be used ", but that's not entirely correct, especially for this case because you will be in control of everything that is going to be evaluated, so you don't run the risks of making aeval
with an unknown input.Based on the answers provided by Álvaro and Jesús (new answers are welcome), I ended up using this code, using variable functions :