动机
控制标记的作用是在于决定是否继续下面流程,但是现代语言注重于使用break 和 continue
确保真实的条件表达式是清晰的
函数的条件逻辑使人难以看清正常的执行路径
使用卫语句表现所有的特殊情况
double getPayAmount() {
double result;
if (_isDead) result = deadAmount();
else {
if (_isSeparated) result = separatedAmount();
else {
if (_isRetired) result = retiredAmount();
else result = normalPayAmount();
};
}
return result;
};
to
double getPayAmount() {
if (_isDead) return deadAmount();
if (_isSeparated) return separatedAmount();
if (_isRetired) return retiredAmount();
return normalPayAmount();
};
动机
如果这个条件是非同寻常的条件,检查这条件是否符合然后返回true
这样大度的检查被称为“卫语句”
对某一条分支已特别的重,如果使用if-then-else 结构,你对if分支和else分支的重要性是同等的
各个分支具有同一样的重要性
取代之前的观念 “每个函数只能有一个入口和一个出口”
你手上有一个条件表达式,它根据对象的类型的不同选择不同的行为
将条件表达式的所有分支放进一个子类内的覆盖函数中,然后将原始函数声明为抽象函数
class Employee {
private int _type;
static final int ENGINEER = 0;
static final int SALESMAN = 1;
static final int MANAGER = 2;
Employee (int type) {
_type = type;
}
int payAmount() {
switch (_type) {
case ENGINEER:
return _monthlySalary;
case SALESMAN:
return _monthlySalary + _commission;
case MANAGER:
return _monthlySalary + _bonus;
default:
throw new RuntimeException("Incorrect Employee");
}
}
}
}
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/tongxinshuyu/article-89441-18.html
爱你一生不后悔
1的不知道要不要升