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. sqlalchemy 入门

    ORM技术:Object-Relational Mapping,把关系数据库的表结构映射到对象上. 在Python中,最有名的ORM框架是SQLAlchemy. # 导入: from sqlalche ...

  2. 嵌入式c语言编码规范

    学习嵌入式的同学应该首先掌握嵌入式编码规范,这样才能更好的嵌入式系统. 下面就从这几个方面讲解一下嵌入式c编码规范. 注释风格.排版风格.头文件风格.变量定义.宏定义.函数 1 注释风格 1.1  注 ...

  3. 吴裕雄--天生自然 pythonTensorFlow图形数据处理:循环神经网络预测正弦函数

    import numpy as np import tensorflow as tf import matplotlib.pyplot as plt # 定义RNN的参数. HIDDEN_SIZE = ...

  4. 云服务器上安装MSF环境

    在校园网内,禁止使用路由器之类的,所以就导致自己本地虚拟机环境出现各种各样的网络问题,解决起来过于繁琐,为此在服务器上安装MSF 0x00 安装MSF 使用Xshell等工具连上远程服务器后,首先确保 ...

  5. SecureCRT8.3

    https://blog.csdn.net/dff1993/article/details/81189610 这篇文章我试过,成功激活了SecureCRT8.3

  6. 远程关机 (Windows shutdown Windows)

    在某些场景,可使用远程关机控制整个局域网中的所有电脑进行一键关机或重启,便于管理,以提高工作效率. 从远程系统强制关机,首先需要进行一些必要的设置. 1.使用 win + R 打开运行,输入gpedi ...

  7. Codeforces Round #579 (Div. 3) Complete the Projects(贪心、DP)

    http://codeforces.com/contest/1203/problem/F1 Examples input 1 - - output 1 YES input 2 - - output 2 ...

  8. mysql,主键与索引的区别和联系

    关系数据库依赖于主键,它是数据库物理模式的基石.主键在物理层面上只有两个用途: 惟一地标识一行. 作为一个可以被外键有效引用的对象. 索引是一种特殊的文件(InnoDB数据表上的索引是表空间的一个组成 ...

  9. jQuery - textarea 自适应内容高度

    <textarea id="textarea"></textarea> <script> function makeExpandingArea( ...

  10. rest framework-分页-长期维护

    ###############  分页组件   ############### # 分页组件 # # django也有分页,rest framework也有分页,但是没有页面这个概念了, # 这个分页 ...