博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
重构-改善既有代码的设计完整笔记系列之9 - 简化条件表达式
阅读量:4135 次
发布时间:2019-05-25

本文共 4632 字,大约阅读时间需要 15 分钟。

  • 9.1 Decompose Conditional(分解条件表达式)
  • 9.2 Consolidate Conditional Expression(合并条件表达式)
  • 9.3 Consolidate Duplicate Conditional Fragments(合并重复的条件片段)
  • 9.4 Remove Control Flag(移除控制标记)
  • 9.5 Replace Nested Conditional with Guard Clauses(以卫语句取代嵌套条件表达式)
  • 9.6 Replace Conditional with Polymorphism(以多态取代条件表达式)
  • 9.7 Introduce Null Object(引入Null对象)
  • 9.8 Introduce Assertion(引入断言)

9.1 Decompose Conditional(分解条件表达式)

分解为多个独立函数,根据每个小块代码的用途,为分解的新函数命名,从而更清楚的表达意图

if (date.before (SUMMER_START) || date.after(SUMMER_END))    charge = quantity * _winterRate + _winterServiceCharge;else charge = quantity * _summerRate;//转变:if (notSummer(date))    charge = winterCharge(quantity);else     charge = summerCharge (quantity);private boolean notSummer(Date date) {    return date.before (SUMMER_START) || date.after(SUMMER_END);}private double summerCharge(int quantity) {    return quantity * _summerRate;}private double winterCharge(int quantity) {    return quantity * _winterRate + _winterServiceCharge;}

9.2 Consolidate Conditional Expression(合并条件表达式)

一系列条件都得到相同结果。则将这些测试合并为一个条件表达式。

double disabilityAmount() {    if (_seniority < 2) return 0;    if (_monthsDisabled > 12) return 0;    if (_isPartTime) return 0;// compute the disability amountdouble disabilityAmount() {    if (isNotEligableForDisability()) return 0;

9.3 Consolidate Duplicate Conditional Fragments(合并重复的条件片段)

在条件表达式的每个分支上有着相同的一段代码。将这段重复代码移到条件表达式之外.

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();

9.4 Remove Control Flag(移除控制标记)

//以break或return语句取代控制标记。    void checkSecurity(String[] people) {        boolean found = false;        for (int i = 0; i < people.length; i++) {            if (!found) {                if (people[i].equals("Don")) {                    sendAlert();                    found = true;                }                if (people[i].equals("John")) {                    sendAlert();                    found = true;                }            }        }    }//替换:    void checkSecurity(String[] people) {        for (int i = 0; i < people.length; i++) {            if (people[i].equals("Don")) {                sendAlert();                break;            }            if (people[i].equals("John")) {                sendAlert();                break;            }        }    }//另外,return也需要合理使用    void checkSecurity(String[] people) {        String found = "";        for (int i = 0; i < people.length; i++) {            if (found.equals("")) {                if (people[i].equals("Don")) {                    sendAlert();                    found = "Don";                }                if (people[i].equals("John")) {                    sendAlert();                    found = "John";                }            }        }        someLaterCode(found);    }//改成:    String foundMiscreant(String[] people) {        for (int i = 0; i < people.length; i++) {            if (people[i].equals("Don")) {                sendAlert();                return "Don";            }            if (people[i].equals("John")) {                sendAlert();                return "John";            }        }        return "";    }

9.5 Replace Nested Conditional with Guard Clauses(以卫语句取代嵌套条件表达式)

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)            result = retiredAmount();        else            result = normalPayAmount();        return result;    }

9.6 Replace Conditional with Polymorphism(以多态取代条件表达式)

一个条件表达式,它根据对象类型的丌同而选择丌同的行为。

将这个条件表达式的每个分支放进一个子类的覆写函数中,然后将原始函数声明为抽象函数。
比如将以下条件都转换成子类

double getSpeed() {        switch (_type) {        case EUROPEAN:            return getBaseSpeed();        case AFRICAN:            return getBaseSpeed() - getLoadFactor() * _numberOfCoconuts;        case NORWEGIAN_BLUE:            return (_isNailed) ? 0 : getBaseSpeed(_voltage);        }        throw new RuntimeException("Should be unreachable");    }

9.7 Introduce Null Object(引入Null对象)

9.8 Introduce Assertion(引入断言)

某一段代码需要对程序状态做出某种假设。以断言明确表现这种假设。

使用断言明确标明对输入条件的严格要求和限制;

断言可以辅助交流和调试。

转载地址:http://tcpvi.baihongyu.com/

你可能感兴趣的文章
链睿和家乐福合作推出下一代零售业隐私保护技术
查看>>
Unifrax宣布新建SiFAB™生产线
查看>>
艾默生纪念谷轮™在空调和制冷领域的百年创新成就
查看>>
NEXO代币持有者获得20,428,359.89美元股息
查看>>
Piper Sandler为EverArc收购Perimeter Solutions提供咨询服务
查看>>
RMRK筹集600万美元,用于在Polkadot上建立先进的NFT系统标准
查看>>
JavaSE_day14 集合中的Map集合_键值映射关系
查看>>
异常 Java学习Day_15
查看>>
Mysql初始化的命令
查看>>
MySQL关键字的些许问题
查看>>
浅谈HTML
查看>>
css基础
查看>>
Servlet进阶和JSP基础
查看>>
servlet中的cookie和session
查看>>
过滤器及JSP九大隐式对象
查看>>
软件(项目)的分层
查看>>
菜单树
查看>>
Servlet的生命周期
查看>>
JAVA八大经典书籍,你看过几本?
查看>>
《读书笔记》—–书单推荐
查看>>