
CLÁUSULAS DE GUARDIA EN PHP
Cuando tenemos que implementar un código que va a tener varias anidaciones va a perder la legibiliad, ya que el código se va a ir demasiado a la derecha debido a la indentación. Otro problema es que cuando tenemos varios "if" con sus respectivos "if" llegará un momento en que no se sepa a que "if" pertenece cada "else".
Veamos el siguiente ejemplo:
public function divide(int $divider): float
{
if ($this->getValue() > 0) {
if ($divider > 0) {
if ( $divider != 1) {
return $this->getValue()/$divider;
} else {
return $this->getValue();
}
} else {
throw new Exception('División por cero.');
}
} else {
return 0;
}
}
public function divide(int $divider): float
{
if ($this->getValue() == 0) {
return 0;
}
if ($divider == 0) {
throw new Exception('División por cero.');
}
if ($divider == 1) {
return $this->getValue();
}
return $this->getValue()/$divider;
}