首页 > 代码库 > 代码重构之引入解释性变量

代码重构之引入解释性变量

意图

  • 临时变量可以帮助你将表达式分解为比较容易管理的形式

  • 在较长的算法中,可以运用临时变量来解释每一步运算的意义

示例

/** * 引入解释性变量之前 * Created by luo on 2017/4/23. */public class IntroduceExplainingVariableBefore {    private String platform;    private String browser;    private int resize = 0;    public void test(){        if ((platform.toUpperCase().indexOf("MAC") > -1) && (browser.toUpperCase().indexOf("IE") > -1) && wasInitialized() && resize > 0){            //do something        }    }    private boolean wasInitialized() {        return false;    }}/** * 引入解释性变量之后 * Created by luo on 2017/4/23. */public class IntroduceExplainingVariableAfter {    private String platform;    private String browser;    private int resize = 0;    public void test() {        final boolean isMacOs = platform.toUpperCase().indexOf("MAC") > -1;        final boolean isIEBrowser = browser.toUpperCase().indexOf("IE") > -1;        final boolean wasResized = resize > 0;        if (isMacOs && isIEBrowser && wasInitialized() && wasResized) {            //do something        }    }    private boolean wasInitialized() {        return false;    }}

 

代码重构之引入解释性变量