重构手法(三)之简化条件表达式
2016-01-27 13:34
281 查看
1、Decompose Conditional(分解条件表达式)
重构前:
重构后:
2、Consolidate Conditional Expression(合并条件表达式)
重构前:
重构后:
3、Consolidate Duplicate Conditional Fragments(合并重复的条件片段)
重构前:
重构后:
4、Remove Control Flag(移除控制标记)
在一系列布尔表达式中,某个变量带有“控制标记”(control flag)的作用。以break语句或return语句取代控制标记。
5、Replace Nested Conditional with Guard Clauses(以卫语句取代嵌套条件表达式)
重构前:
重构后:
6、Replace Conditional with Polymorphism(以多态取代条件表达式)
7、Introduce Null Object(引入Null对象)
8、Introduce Assertion(引入断言)
重构前:
if(date.before(SUMMER_START) || date.after(SUMMER_END)) charge = quantity * _winterRate + _winterServiceCharge; else charge = quantity * _summerRate;
重构后:
if(notSummer(date)) charge = winterCharge(quantity); else charge = summerCharge(quantity);
2、Consolidate Conditional Expression(合并条件表达式)
重构前:
double disabilityAmount(){ if(_seniority < 2) return 0; if(_monthsDisabled > 12) return 0; if(_isPartTime) return 0; //computer the disability amount }
重构后:
double disabilityAmount(){ if(isNotEligableForDisablity()) return 0; //computer the disablity amount }
3、Consolidate Duplicate Conditional Fragments(合并重复的条件片段)
重构前:
if(isSpecialDeal()){ total = price * 0.95; send(); } else{ total = price * 0.98; send(); }
重构后:
if(isSpecialDeal()){ total = price * 0.95; } else{ total = price * 0.98; } send();
4、Remove Control Flag(移除控制标记)
在一系列布尔表达式中,某个变量带有“控制标记”(control flag)的作用。以break语句或return语句取代控制标记。
5、Replace Nested Conditional with Guard Clauses(以卫语句取代嵌套条件表达式)
重构前:
double getPayAmount(){ double result; if(_isDead) result = deadAmount(); else{ if(_isSeparated) result = separatedAmount(); else{ if(_isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; }
重构后:
double getPayAmount(){ if(_isDead) return deadAmount(); if(_isSeparated) return separatedAmount(); if(_isRetired) return retiredAmount(); return normalPayAmount(); }
6、Replace Conditional with Polymorphism(以多态取代条件表达式)
7、Introduce Null Object(引入Null对象)
8、Introduce Assertion(引入断言)
相关文章推荐
- touchmove Bug 工作遇到
- cocos2dx-IOS微信分享
- erlang 用rfc4627 带中文的json格式
- 1.CocoaPods的安装
- python 输出表达式之format
- HDU 1022 Train Problem I
- 集合类型
- 面试笔试杂项积累-leetcode 11-15
- Xcode调试技巧(断点和重构)
- C语言学习之程序运行是内存的5大分区
- linux常用命令2
- Wireshark
- Mongodb 和Redis 的相同点和不同点
- 《1》7层+4层网络模型
- 信息流聚合类系统(如RSS阅读器)中数据同步的架构设计
- 提取URL的搜索字符串中的参数
- Closeable
- curlPost
- IOS平台各种解析XML库的优缺点分析
- Android开发中出现in the gradle.properties file, sets the maximum Java heap size to 1024m的解决方法