1. 分解条件表达式
if (isUp(case) || isLeft(case))
num = a * b;
else num = a * c;
更改为↓
if (isTrue(case))
numberB(a);
else numberC(a);
boolean isTrue(case) {
return isUp(case) || isLeft(case);
}
int numberB(a) {
return a + b;
}
int numberC(a) {
return a + c;
}
2. 合并条件表达式
double disabukutyAmount() {
if (_seniority < 2) return 0;
if (_monbtdiable > 12) return 0;
if (_isPartyTime) retutn 0;
}
更改为↓
double disablilityAmount() {
if (isNotEligibleForDisability()) return 0;
}
boolean isNotEligibleForDisability() {
return _seniority < 2 || _monbtdiable > 12 || _isPartyTime;
}
3. 合并重复的条件片段
有时候你可能会在if else 语句中写重复的语句,这时候你需要将重复的语句抽出来。
if (isSpecialDeal()) {
total = price * 0.95;
send();
} else {
total = price * 0.98;
send();
}
更改为↓
if (isSpecialDeal())
total = price * 0.95;
else
total = price * 0.98;
send();
4.移除控制标记
5. 以卫语句取代嵌套表达式
加入return语句去掉else语句。
if (a > 0) result = a + b;
else {
if (b > 0) result = a + c;
else {
result = a + d;
}
}
return result;
更改为↓
if (a > 0) return a + b;
if (b > 0) return a + c;
return a + d;
6. 以多态取代switch语句
将条件表达式的每个分支放入一个子类的覆写函数中,将原始函数声明为抽象函数
int getArea() {
switch (_shap)
case circle:
return 3.14 * _r * _r; break;
case rect;
return _width + _heigth;
}
更改为↓
class Shap {
int getArea(){};
}
class Circle extends Shap {
int getArea() {
return 3.14 * _r * _r; break;
}
}
class Rect extends Shap {
int getArea() {
return _width + _heigth;
}
}
7.引入null对象
需要检查对象是否为空,将null值替换为null对象
if(customer == null){
plan=BillingPlan.basic();
}else{
plan = customer.getPlan();
}
做法:
为源类建立一个子类,使其行为就像是源类的null版本,在源类和null子类中都加上isNUll()函数,牵着的isNull返回false,后者的返回true
建立一个nullable接口,把isnull函数放入,源类实现。
8.引入断言
某一段代码需要对程序状态做出某种假设,以断言明确表现这种假设。
double getExpenseLimit(){
return (expenseLimit !=NULL_EXPENSE )?expenseLimit:primaryProject.getMemberExpenseLimit;
}
double getExpenseLimit(){
Assert.isTrue(expenseLimit !=NULL_EXPENSE&&primaryProject!=null);
return (expenseLimit !=NULL_EXPENSE )?expenseLimit:primaryProject.getMemberExpenseL
}