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. 扯下Python的super()

    注: Python 2.7.x 环境下 今晚搜东西无意中看到这篇Understanding Python super() with __init__() methods. 其实这篇老早就看过了, 不过 ...

  2. ZEOSDBO控件的安装及使用方法

    步骤:1:下载最新版的ZEOSDBO,官网:http://sourceforge.net/projects/zeoslib/ 2:解压文件到文件安装目录下:C:\Program Files\Embar ...

  3. Codeforces Round #556(Div.1)

    A 容易发现i,i+1至少有一个数出现,于是可以让尽量多的2和奇数出现 #include<bits/stdc++.h> using namespace std; int n,s1,s2; ...

  4. poj-3658 Artificial Lake(模拟)

    http://poj.org/problem?id=3658 Description The oppressively hot summer days have raised the cows' cl ...

  5. centos jdk

    yum list java* yum install xxx -y java -version /* 可省略 */ vi /etc/profile export JAVA_HOME=/usr/lib/ ...

  6. python数据类型:字符串

    字符串是python中最常见的数据类型,使用单引号或双引号创建字符串 python不支持单字符类型,单字符在python中也是字符串 文档原文:http://www.runoob.com/python ...

  7. 解决scoped 下confirm 样式问题

  8. 文件加密,密码加密,os模块

    序列化模块 (非常非常重要) 序列化:将一个数据结构(list,dict....)转化成一个特殊的序列(特殊的字符串)的过程. # l1 = [1, 2, 3] # ret = str(l1) # p ...

  9. python语法基础-函数-进阶-长期维护

    ###############    函数的命名空间和作用域    ############## """ # 函数进阶 命名空间和作用域 命名空间 全局命名空间——我们自 ...

  10. linux下添加行数和修改tab空格数

    在/etc/vimrc文件中添加: set nu set ts=4 保存即可