简化条件表达式
来源:互联网 发布:单词社交网络视频 编辑:程序博客网 时间:2024/04/28 22:08
1. 分解条件表达式
if (isUp(case) || isLeft(case)) num = a * b;else num = a * c;更改为↓if (isTrue(case)) numberB(a);else numberC(a);boolean isTrue(case) { return isUp(case) || isLeft(case);}int numberB(a) { return a + b;}int numberC(a) { return a + c;}
2. 合并条件表达式
double disabukutyAmount() { if (_seniority < 2) return 0; if (_monbtdiable > 12) return 0; if (_isPartyTime) retutn 0;}更改为↓double disablilityAmount() { if (isNotEligibleForDisability()) return 0;}boolean isNotEligibleForDisability() { return _seniority < 2 || _monbtdiable > 12 || _isPartyTime;}
3. 合并重复的条件片段
有时候你可能会在if else 语句中写重复的语句,这时候你需要将重复的语句抽出来。
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.移除控制标记
5. 以卫语句取代嵌套表达式
加入return语句去掉else语句。
if (a > 0) result = a + b;else { if (b > 0) result = a + c; else { result = a + d; }}return result;更改为↓if (a > 0) return a + b;if (b > 0) return a + c;return a + d;
6. 以多态取代switch语句
将条件表达式的每个分支放入一个子类的覆写函数中,将原始函数声明为抽象函数
int getArea() { switch (_shap) case circle: return 3.14 * _r * _r; break; case rect; return _width + _heigth;}更改为↓class Shap { int getArea(){};}class Circle extends Shap { int getArea() { return 3.14 * _r * _r; break; }}class Rect extends Shap { int getArea() { return _width + _heigth; }}
7.引入null对象
需要检查对象是否为空,将null值替换为null对象
if(customer == null){plan=BillingPlan.basic();}else{plan = customer.getPlan();}
做法:
为源类建立一个子类,使其行为就像是源类的null版本,在源类和null子类中都加上isNUll()函数,牵着的isNull返回false,后者的返回true
建立一个nullable接口,把isnull函数放入,源类实现。
8.引入断言
某一段代码需要对程序状态做出某种假设,以断言明确表现这种假设。
double getExpenseLimit(){return (expenseLimit !=NULL_EXPENSE )?expenseLimit:primaryProject.getMemberExpenseLimit;}double getExpenseLimit(){Assert.isTrue(expenseLimit !=NULL_EXPENSE&&primaryProject!=null);return (expenseLimit !=NULL_EXPENSE )?expenseLimit:primaryProject.getMemberExpenseL}
阅读全文
0 0
- 简化条件表达式
- 简化条件表达式
- 简化条件表达式
- 4、简化条件表达式
- 简化条件表达式
- 第九章 简化条件表达式
- 简化条件表达式(一)
- 简化条件表达式(二)
- 第九章简化条件表达式
- 重构--简化条件表达式
- 重构之简化条件表达式
- 重构系列6.简化条件表达式
- 重构之简化条件表达式
- 重构之简化条件表达式2
- 重构代码-简化条件表达式
- 重构之简化条件表达式
- 简化条件表达式之一 :Decompose Conditional(分解条件式)
- 简化条件表达式之八 :Introduce Assertion(引入断言)
- 树莓派修改静态IP(亲测可用)
- android系统架构图及各层介绍
- Linux-C语言编程-Day-1
- VS2015静态库的使用(下)
- 课程期末作业:《算法概论》课后8.16题的证明
- 简化条件表达式
- WindowBuilder:A plugin of Eclipse to design GUI -- 玩转Eclipse
- 浅谈WebLogic和Tomcat
- hdu4507(数位dp,较复杂)
- Cannot determine embedded database driver class for database type NONE
- 设计模式(九)builder
- mentohust多进程
- 合理的配置线程池线程数
- SCP 提示 Permission denied, please try again.解决方法