函数中的条件逻辑使人难以看清正常的执行路径
double getPayAmount() {double result;if (isDead) {result = deadAmount();} else {if (isSeparated) {result = separatedAmount();} else {if (isRetired) {result = retiredAmount();} else {result = normalPayAmount()}}}return result;
}
重构:使用卫语句表现所有特殊情况
double getPayAmount() {double result;if (isDead) {return deadAmount();} if (isSeparated) {return separatedAmount();}if (isRetired) {return retiredAmount();}return normalPayAmount();
}
动机
条件表达式通常有两种表现形式
1、所有分支都属于正常行为;
2、条件表达式中只有一个是正常行为
这两类条件表达式有不同的用途,这一点应该通过代码表现出来。
如果两条分支都是正常行为,应该使用if...else...
如果某个条件极其罕见,应该单独检查该条件,并在其true 时立刻return。——这样的单独检查被称为“卫语句”(guard clauses)