• 重构16-Encapsulate Conditional(封装条件)


    当代码中充斥着若干条件判断时,代码的真正意图会迷失于这些条件判断之中。这时我喜欢将条件判断提取到一个易于读取的属性或方法(如果有参数)中。重构之前的代码如下:

    public class RemoteControl {
    private String[] Functions;//getter setter
    private String Name;//getter setter
    private int CreatedYear;//getter setter

    public String PerformCoolFunction(String buttonPressed) {
    // Determine if we are controlling some extra function
    // that requires special conditions
    if (Functions.length > 1 && Name == "RCA" && CreatedYear > new Date().getYear() - 2) {
    return "doSomething";
    }
    return null;
    }
    }
    重构之后,代码的可读性更强,意图更明显:
    public class RemoteControl {
    private String[] Functions;//getter setter
    private String Name;//getter setter
    private int CreatedYear;//getter setter
    private Boolean HasExtraFunctions;

    public Boolean getHasExtraFunctions() {
    return Functions.length > 1 && Name == "RCA" && CreatedYear > new Date().getYear() - 2;
    }
    public String PerformCoolFunction(String buttonPressed) {
    // Determine if we are controlling some extra function
    // that requires special conditions
    if (HasExtraFunctions) {
    return "doSomething";
    }
    return null;
    }
    }





  • 相关阅读:
    MSP430开学的序章
    此地不留爷,自有留爷处
    【javascript】继承
    【css】css3属性
    【计划】合格的前端
    【grunt】grunt 基础学习
    【防火墙】防火墙分类,过滤流程
    【js】name 与 array 的纠葛
    【TRICK】解决锚点定位向下浮动Xpx问题
    【性能】web提升性能的小总结
  • 原文地址:https://www.cnblogs.com/jgig11/p/5786338.html
Copyright © 2020-2023  润新知