zoukankan      html  css  js  c++  java
  • 重构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;
    }
    }





  • 相关阅读:
    Android开发系列之ListView用法
    自省
    fake feeling ?
    我心中的天使
    2020.6.16
    python面试题
    tcp
    Short + skip + limit
    01_pyttsx3_将文本文字转为语音播放
    mongo_Linux下不进入数据库查数据
  • 原文地址:https://www.cnblogs.com/jgig11/p/5786338.html
Copyright © 2011-2022 走看看