zoukankan      html  css  js  c++  java
  • 重构26-Remove Double Negative(去掉双重否定)

    尽管我在很多代码中发现了这种严重降低可读性并往往传达错误意图的坏味道,但这种重构本身还是很容易实现的。这种毁灭性的代码所基于的假设导致了错误的代码编写习惯,并最终导致bug。如下例所示:
    public class Order {
    public void Checkout(List<Product> products, Customer customer) {
    if (!customer.getNotFlagged()) {
    // the customer account is flagged
    // log some errors and return
    return;
    }
    // normal order processing
    }
    }
    public class Customer {
    public Double Balance;
    public Boolean IsNotFlagged;

    public Boolean getNotFlagged() {
    return Balance < 30d;
    }
    public void setNotFlagged(Boolean notFlagged) {
    IsNotFlagged = notFlagged;
    }
    }
    如你所见,这里的双重否定十分难以理解,我们不得不找出什么才是双重否定所要表达的肯定状态。修改代码是很容易的。如果我们找不到肯定的判断,可以添加一个处理双重否定的假设,而不要在得到结果之后再去验证。
    public class Order {
    public void Checkout(List<Product> products, Customer customer) {
    if (customer.getFlagged()) {
    // the customer account is flagged
    // log some errors and return
    return;
    }
    // normal order processing
    }
    }
    public class Customer {
    public Double Balance;
    public Boolean IsFlagged;

    public Boolean getFlagged() {
    return Balance < 30d;
    }
    public void setFlagged(Boolean Flagged) {
    IsFlagged = Flagged;
    }
    }





  • 相关阅读:
    a.default.ERROR.httpAjax is not a function
    Java heap space
    jmeter
    sql注入
    数据库查前三名
    maven
    国际化变现应用分析
    百度应用部署秘籍
    如何建立起一套有效的APP监控体系
    第三方舆情收集与质量闭环建设
  • 原文地址:https://www.cnblogs.com/jgig11/p/5786447.html
Copyright © 2011-2022 走看看