
最常用的逻辑语句非 if else
莫属。大量使用 if else
容易编写出逻辑混乱的代码。这种代码令阅读者云里雾里,维护者心力交瘁。
让我们来看一组案例:
public function charge(DateTimeImmutable $time)
{
if ($time > (new DateTimeImmutable('now'))) {
$this->deductAmountWithPenalty();
} else {
$this->deductNormalAmount();
}
}
public function creditUser(User $user)
{
if ($user->is_active) {
if (0 !== $user->credits) {
$user->credits++;
} else {
$user->credits = 0;
}
}
}
根据代码规范,每一个 if
或者 else
的内容必须在左边预留空间,从而促使我们的注意力从左向右地移动,而每一个 if else
嵌套会造成更多的左边空间。
相比从左向右的,从上至下是更适合阅读的。
这时候我们可以使用 return
来重构我们的代码:
public function charge(DateTimeImmutable $time)
{
if ($time > (new DateTimeImmutable('now'))) {
$this->deductAmountWithPenalty();
return;
}
$this->deductNormalAmount();
}
public function creditUser(User $user)
{
if (!$user->is_active) {
return;
}
if (0 !== $user->credits) {
$user->credits++;
return;
}
$user->credits = 0;
}
重构以后,我们的代码逻辑没有任何改变。但是代码的易读性不管是逻辑上还是美观上都有了大大的提高。
我们用 return
取代了 else
的判断。
利用趁早 return
,每个 return
都成为了一个结束条件,在阅读的时候我们不必回忆上文中的 else
。
代码由原来的从左向右增长,变成了从上向下增长,这样子更适合阅读。