简化条件表达式


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
		}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值