本文内容参照refactoring.com, 有英文好的同学,可以直接去英文网站上浏览内容。转载请附上地址及原网站。重构在软件开发中是一个非常重要的手段。重构可以使代码更加精炼,提高代码的可读性。下面我会就以下几个方面介绍一下一般重构的几种方式。同时,也会简单介绍使用IDE进行重构的快捷键。
一、如何重构
1. 基本内容
1) 修改方法声明
- 添加(移除)参数
-
修改(重命名)方法名
Change Function Declaration
2)提取变量
与提取变量反方向的动作是3)

Extract Variable
3)将提取的变量变成表达式
与提取变量反方向的动作是2)

Inline Variable
4) 用类组织方法

Combine Functions into Class
5) 封装变量

Encapsulate Variable
6)将函数组合到变换中

Combine Functions into Transform
7)介绍参数对象

Introduce Parameter Object
8)将功能相同的代码块抽成函数
与其反方向的动作是9)

Extract Function
9)将函数中的代码块替换到函数调用的位置
与其反方向的动作是8)

Inline Function
10)重命名变量名

Rename Variable
2. 封装
1)抽类(将类细化),设计模式中单一模式原则
与其反方向的动作是2)

Extract Class
2)将两个类合并成一个类
与其反方向的动作是1)

Inline Class
3) 封装集合

Encapsulate Collection
4)移除中间人
与其相反的操作是9)

Remove Middle Man
5)使用数据类替换数据记录

Encapsulate Record
6)用对象代替数据值,用类代替类型

Replace Primitive with Object
7) 用函数代替临时值

Replace Temp with Query
8) 替代算法

Substitute Algorithm
9 隐藏委托
与其相反的操作是4)

Hide Delegate
3. 移动
1) 移动字段

Move Field
2) 用方法调用代替内联代码

Replace Inline Code with Function Call
3) 移动方法

Move Function
4) 用Pipeline代替循环

Replace Loop with Pipeline
5)将声明移动到方法中
与其相反的操作是6)

Move Statements into Function
6)将声明移动到调用者的位置
与其相反的操作是5)

Move Statements to Callers
7) 合并重复的条件片段

Slide Statements
8)将一个循环中的两条语句分到两个循环中

Split Loop
9)移除不起任何作用的代码

Remove Dead Code
10)分阶段

Split Phase
4. 组织数据
1) 变引用为值

Change Reference to Value
2)变值为引用

Change Value to Reference
3)用查询代替衍生变量

Replace Derived Variable with Query
4)代替魔法数

Replace Magic Literal
5)分变量

Split Variable
6) 重命名字段

Rename Field
5. 简化条件逻辑
1)合并条件表达式

Consolidate Conditional Expression
2)用多态替换条件

Replace Conditional with Polymorphism
3)简化条件

Decompose Conditional
4)使用break代替控制标志

Replace Control Flag with Break
5) 介绍断言

Introduce Assertion
6)用同级条件判断代替嵌套条件判断

Replace Nested Conditional with Guard Clauses
7)介绍空对象

Introduce Special Case
6. 重构apis
1) 参数化方法

Parameterize Function
2) 用提前校验代替异常

Replace Exception with Precheck
3) 保留对象

Preserve Whole Object
4) 用命令代替方法

Replace Function with Command
5)移除旗帜参数

Remove Flag Argument
6) 用查询代替参数

Replace Parameter with Query
7) 移除set方法

Remove Setting Method
8) 用参数代替查询

Replace Query with Parameter
9) 用方法代替命令

Replace Command with Function
10) 返回修改的值

Return Modified Value
11) 用工厂方法代替构造器

Replace Constructor with Factory Function
12)从修饰语中分离出查询

Separate Query from Modifier
13) 用异常代替错误码

Replace Error Code with Exception
7. 处理继承
1) 合并继承层次

Collapse Hierarchy
2) 方法降到子类

Push Down Method
3)子类中相同方法提到父类

Pull Up Method
4)抽父类

Extract Superclass
5) 移除子类

Remove Subclass
6) 属性的构造要在合适的类中完成

0707.png

Pull Up Constructor Body
7)用委托代替子类

Replace Subclass with Delegate
8) 将共同的属性提到父类中

Pull Up Field
9)用委托代替父类
[图片上传失败...(image-728a7-1543624221676)]
](https://img.haomeiwen.com/i7085065/d43b279aab88c028.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
10) 用子类代替类型码

Replace Type Code with Subclasses
11) 用子类代替类型码

Replace Type Code with Subclasses
网友评论