重构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() - ) {
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() - ;
}
public String PerformCoolFunction(String buttonPressed) {
// Determine if we are controlling some extra function
// that requires special conditions
if (HasExtraFunctions) {
return "doSomething";
}
return null;
}
}
上一篇:WRITING POSTGRESQL TRIGGERS IN GO


下一篇:开机或联网时自启动gunicorn