1.Decompose Conditional(分解条件表达式)

2.Consolidate Conditional Expressions(合并条件表达式)

3.Consolidate Duplicate Conditional Fragments(合并重复的条件片段)

4.Remove Control Flag(移除控制标记)

5.Replace Nested Conditional with Guard Clauses(以卫语句取代嵌套条件表达式)

6.Replace Conditional with Polymorphism(以多态取代条件表达式)

7.Introduce Null Object(引入null对象)

8.Indroduce Assertion(引入断言)

1.Decompose Conditional(分解条件表达式)

当有复杂的if else判断时,应该将条件判断抽成方法,使代码思路更清晰,即使是简短的判断,抽成方法也会对代码的可读性起到很大的提升作用.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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);
private boolean (Date date) {
return date.before (SUMMER_START) || date.after(SUMMER_END);
}
private double summerCharge(int quantity) {
return quantity * _summerRate;
}
private double winterCharge(int quantity) {
return quantity * _winterRate + _winterServiceCharge;
}

像这个例子不知道会不会有点过头了?

2.Consolidate Conditional Expressions(合并条件表达式)

当众多条件的结果是一样时,应将其合并为一个方法.

1
2
3
4
5
6
7
8
9
10
11
12
double disabilityAmount() {
if (_seniority < 2) return 0;
if (_monthsDisabled > 12) return 0;
if (_isPartTime) return 0;
}
---------
double disabilityAmount() {
if (isNotEligableForDisability()) return 0;
}
boolean isNotEligibleForDisability() {
return ((_seniority < 2) || (_monthsDisabled > 12) || (_isPartTime));
}

3.Consolidate Duplicate Conditional Fragments(合并重复的条件片段)

条件判断中相同部分的代码应该移出条件表达式,这样你能看出来哪些是一样的哪些是不一样的。

1
2
3
4
5
6
7
8
9
10
11
12
13
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(移除控制标记)

可以使用break,continue或return来替换控制标签,增强代码可读性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
void checkSecurity(String[] people) {
boolean found = false;
for (int i = 0; i < people.length; i++) {
if (! found) {
if (people[i].equals ("Don")){
sendAlert();
found = true;
}
if (people[i].equals ("John")){
sendAlert();
found = true;
}
}
}
}
------
void checkSecurity(String[] people) {
for (int i = 0; i < people.length; i++) {
if (people[i].equals ("Don")){
sendAlert();
break;
}
if (people[i].equals ("John")){
sendAlert();
break;
}
}
}
//example2
void checkSecurity(String[] people) {
String found = "";
for (int i = 0; i < people.length; i++) {
if (found.equals("")) {
if (people[i].equals ("Don")){
sendAlert();
found = "Don";
}
if (people[i].equals ("John")){
sendAlert();
found = "John";
}
}
}
someLaterCode(found);
}
----------
void checkSecurity(String[] people) {
String found = foundMiscreant(people);
someLaterCode(found);
}
String foundMiscreant(String[] people){
for (int i = 0; i < people.length; i++) {
if (people[i].equals ("Don")){
sendAlert();
return "Don";
}
if (people[i].equals ("John")){
sendAlert();
return "John";
}
大专栏  Simplifying Conditional Expressions(简化条件表达式)v class="line"> }
return "";
}

5.Replace Nested Conditional with Guard Clauses(以卫语句取代嵌套条件表达式)

用卫语句代替所有特殊的case。卫语句:check the condition and return if the condition is true

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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(以多态取代条件表达式)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Employee...
int payAmount() {
return _type.payAmount(this);
switch (getType()) {
case EmployeeType.ENGINEER:
return _monthlySalary;
case EmployeeType.SALESMAN:
return _monthlySalary + _commission;
case EmployeeType.MANAGER:
return _monthlySalary + _bonus;
default:
throw new RuntimeException("Incorrect Employee");
}
}
int getType() {
return _type.getTypeCode();
}
private EmployeeType _type;
-------------------------------
abstract class EmployeeType...
abstract int getTypeCode();
abstract int payAmount(Employee emp);
class Engineer extends EmployeeType...
int getTypeCode() {
return Employee.ENGINEER;
}
int payAmount(Employee emp) {
return emp.getMonthlySalary();
}
class Salesman...
int payAmount(Employee emp) {
return emp.getMonthlySalary() + emp.getCommission();
}
class Manager...
int payAmount(Employee emp) {
return emp.getMonthlySalary() + emp.getBonus();
}

7.Introduce Null Object(引入null对象)

当每次取数据时如果都要去判空的话会非常耗体力,并且代码非常难看,还有可能有漏掉的情况。这时可以引入一个null对象来解决,null是在对象没有值时的默认值,省去判空的动作,easying+happy呀

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Site...
Customer getCustomer() {
return _customer;
}
Customer _customer;
class Customer...
public String getName() {...}
public BillingPlan getPlan() {...}
public PaymentHistory getHistory() {...}
public class PaymentHistory...
int getWeeksDelinquentInLastYear()
//example
Customer customer = site.getCustomer();
BillingPlan plan;
if (customer == null) plan = BillingPlan.basic();
else plan = customer.getPlan();
String customerName;
if (customer == null) customerName = "occupant";
else customerName = customer.getName();
int weeksDelinquent;
if (customer == null) weeksDelinquent = 0;
else weeksDelinquent = customer.getHistory().getWeeksDelinquentInLastYear();
---------
class Customer...
static Customer newNull() {
return new NullCustomer();
}
class NullCustomer extends Customer {
public boolean isNull() {
return true;
}
public String getName(){
return "occupant";
}
}
class Site...
Customer getCustomer() {
return (_customer == null) ? Customer.newNull(): _customer;
}
//当NullCustomer有自己的getName方法时
String customerName = customer.getName();

8.Indroduce Assertion(引入断言)

通过断言来调试

1
2
3
4
5
6
7
8
9
10
11
12
13
double getExpenseLimit() {
// should have either expense limit or a primary project
return (_expenseLimit != NULL_EXPENSE) ?
_expenseLimit: _primaryProject.getMemberExpenseLimit();
}
----------
double getExpenseLimit() {
Assert.isTrue (_expenseLimit != NULL_EXPENSE || _primaryProject!= null);
return (_expenseLimit != NULL_EXPENSE) ?
_expenseLimit: _primaryProject.getMemberExpenseLimit();
}

Simplifying Conditional Expressions(简化条件表达式)的更多相关文章

  1. shell之条件表达式

    conditional expressions are used by the [[ compound command and the test and [ builtin commands. ari ...

  2. Conditional Expressions

    Conditional Expressions建立一些逻辑关系 The conditional expression classes from django.db import models clas ...

  3. [Django]模型提高部分--聚合(group by)和条件表达式+数据库函数

    前言:本文以学习记录的形式发表出来,前段时间苦于照模型聚合中group by 找了很久,官方文章中没有很明确的说出group by,但在文档中有提到!!! 正文(最后编辑于2016-11-12): 聚 ...

  4. golang没有条件表达式?:

    详见The Go Programming Language Specification中Expressions一章中未提及此表达式, 故其不支持. 再强调一次, GO不支持条件表达式 conditio ...

  5. [Inside HotSpot] C1编译器优化:条件表达式消除

    1. 条件传送指令 日常编程中有很多根据某个条件对变量赋不同值这样的模式,比如: int cmov(int num) { int result = 10; if(num<10){ result ...

  6. Python3笔记012 - 3.3 条件表达式

    第3章 流程控制语句 3.3 条件表达式 在程序开发中,经常会根据表达式的结果,有条件地进行赋值. # 返回两个数中较大的数 a = 10 b = 6 if a>b: r = a else: r ...

  7. Scala:条件表达式的好处

    条件表达式的好处之一是:让代码更简洁,例如在一个需要根据不同条件收集不同值的场景中,多数语言提供的代码如下: ; ) { tmp = xxx; } ) { tmp = yyy; } else { tm ...

  8. Shell 条件表达式汇总

    条件表达式 文件表达式 if [ -f  file ]    如果文件存在if [ -d ...   ]    如果目录存在if [ -s file  ]    如果文件存在且非空 if [ -r f ...

  9. Python学习教程(learning Python)--3.3 分支语句的条件表达式详解

    本节主要讨论分支语句的条件表达式问题. 在if或者if-else分支控制语句里由于都用到条件判断(表达式是真还是假),条件判断可以是一种关系运算也可以是布尔表达式. 本节将对if及if-else语句的 ...

随机推荐

  1. linuxmint截图

    利用import命令截图,并设置快捷键 shift + PrtScrSysRq: 选中区域截图. 设置快捷键的时候,提示: Ctrl + PrtScrSysRq: 复制截图到剪切板 PrtScrSys ...

  2. Debian8.8为普通用户添加sudo权限

    1.进入root用户,su root 输入密码,我们首先修改 /etc/sudoers 文件的属性为可写权限# chmod +w /etc/sudoers2.编辑 vim /etc/sudoers,添 ...

  3. vitual box 虚拟机调整磁盘大小 resize partiton of vitual os

    key:vitual box, 虚拟机,调整分区大小 引用:http://derekmolloy.ie/resize-a-virtualbox-disk#prettyPhoto 1. 关闭虚拟机,找到 ...

  4. 5G时代将至,哪些改变会随之而来?

    近年来,运营商不断被唱衰.关键原因就在于运营商的各项业务,在互联网的冲击下已经愈发"萎缩".尤其是短信和语音通话,它们的价值在不断被降低.简而言之,运营商似乎成为了纯粹的" ...

  5. B-Tree(B树)原理及C++代码实现

    B树是一种平衡搜索树,它可以看做是2-3Tree和2-3-4Tree的一种推广.CLRS上介绍了B树目前主要针对磁盘等直接存取的辅存设备,许多数据库系统也利用B树或B树的变种来存储信息. 本文主要针对 ...

  6. iOS UIWebView 允许所有三方cookie

    前几天项目中用到UIWebView, 而在网页中,用到了多说评论的第三方.但是当我在手机端发表评论的时候,出现禁用第三方cookie,而安卓是没有这种情况的,于是就在找原因.找了很久也没有找到原因.一 ...

  7. 极简配置,业务上云只需 3min

    为了简化账号配置环节,实现本地一键开发部署,Serverless Framework 发布了微信扫码一键登录能力,支持用户在 Serverless Framework 环境扫码注册登陆,用户无需登录控 ...

  8. 服务端向客户端推送消息技术之websocket的介绍

    websocket的介绍 在讲解WebSocket前,我们先来看看下面这种场景,在HTTP协议下,怎么实现. 需求: 在网站中,要实现简单的聊天,这种情况怎么实现呢?如下图: 当发送私信的时候,如果要 ...

  9. 线程中调用service方法出错

    public class PnFileTGIComputeThread implements Runnable { @Resource private AppUsedService appUsedSe ...

  10. nginx做正向代理搭建bugfree

    下载地址: Nginx下载地址:http://download.csdn.net/detail/terrly88/9099117 bugfree下载地址:http://download.csdn.ne ...