重构16-Encapsulate Conditional(封装条件)
2016-08-19 09:32
344 查看
当代码中充斥着若干条件判断时,代码的真正意图会迷失于这些条件判断之中。这时我喜欢将条件判断提取到一个易于读取的属性或方法(如果有参数)中。重构之前的代码如下:
重构之后,代码的可读性更强,意图更明显:
来自为知笔记(Wiz)
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; } }
来自为知笔记(Wiz)
相关文章推荐
- 重构15-Remove Duplication(删除重复)
- centos7 安装redis3.06
- listview多种类型条目显示
- Centos7.x系列密码遗忘重置问题
- linux vi命令详解
- 条件查询List集合,由查询的结果,算出一行数据,添加到集合中!
- 详解Angular中$cacheFactory缓存的使用
- startActivityForResult 没有反应
- android mvp模式 总结及个人心得
- Qt实现图片移动
- border-image属性分析
- 使用有源匹配电路改善宽带全差分放大器的噪声性能
- SQL SERVER 修改数据库名称(包括 db.mdf 名称的修改)
- 重构14-Break Responsibilities
- 重构13-Extract Method Object(提取方法对象)
- 重构12-Break Dependencies(打破依赖)
- JSPatch实现原理
- 《Motion Design for iOS》(四十六(最终章))
- XML 读取
- 重构11-Switch to Strategy(Switch到策略模式)