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字典基础

  2. Kubernetes系列二: 使用kubeadm安装k8s环境

    环境 三台主机,一台master,两台node 作为master 作为node节点 作为node节点 每台主机Centos版本使用 CentOS Linux release 7.6.1810 (Cor ...

  3. tesseract系列(1) -- tesseract用vs编译成库

    1.下载teseract 下载地址github:     https://github.com/tesseract-ocr/tesseract/releases/ 2.编译源码 源码的编译有两种方式 ...

  4. 搭建WordPress个人博客

    1. 准备LNMP环境 LNMP 是 Linux.Nginx.MySQL 和 PHP 的缩写,是 WordPress 博客系统依赖的基础运行环境.我们先来准备 LNMP 环境 安装Nginx 使用 y ...

  5. 用原生socket发送HTTP数据包

    分享一个写扫描器和POC时的小技巧. 有时候有的漏洞需要一些特殊的数据包,比如说畸形的HTTP头.畸形的Multipart.畸形的chunk包等,此时用编程语言自己的HTTP库可能构造不出这种数据包, ...

  6. LGOJ3327 【SDOI2015】约数个数和

    又是一道卡常好题 坑掉我的 \(define \space int \space long \space long\) 感觉出题人并没有获得什么快乐-- Description link 题意概述: ...

  7. 多因素线性回归|adjusted R^2|膨胀系数|非线性回归|Second-order model with 1 independent variable|Interaction model with 2 independent variables|偏相关|fraction[a]|contribution

    多因素线性回归 系数由最小二乘法得到 R^2;adjusted R^2:变量变多之后,r^2自然变大,但是这不是反应客观事实,所以引入了adjusted R^2 使用散点图看独立性,也可以使用软件,c ...

  8. 解决2013Lost connection to MySQL server during query错误方法

    在my.ini配置文件 mysqld 节点下添加 max_allowed_packet = 500M 也就是配置MySQL允许的最大数据包大小,上面的500M你可以根据你的项目修改为你自己的值,只要比 ...

  9. [Windows] Access SMBIOS

    SMBIOS architecture System Management BIOS (SMBIOS) is the premier standard for delivering managemen ...

  10. MySQL 之全文索引

    最近在复习数据库索引部分,看到了 fulltext,也即全文索引,虽然全文索引在平时的业务中用到的不多,但是感觉它有点儿意思,所以花了点时间研究一下,特此记录. 引入概念通过数值比较.范围过滤等就可以 ...