重构

代码的坏味道

Duplicated Code(重复代码)

如果你在一个以上的地方看见相同的程序结构,将它们合二为一。

Long Method(过长函数)

将过长的函数分解为若干个小函数。

Large Class(过大的类)

单个类要做的事情太多,将其分解为几个类。

Long Parameter List(过长参数列)

如果参数太多,考虑使用参数对象。

Divergent Change(发散式变化)

某个类经常因为不同的原因在不同的方向上发生变化。当你看见一个类说:“新加入一个数据库,我必须修改三个函数”

Shotgun Surgery(霰弹式修改)

如果每遇到某种变化,你都必须在许多不同的类中做出许多小修改。

Feature Envy(依恋情结)

函数对某个类的兴趣高过于对自己所处类的兴趣。

Data Clumps(数据泥团)

常在许多地方看到成群的数据,考虑将其抽取为类。

Primitive Obsession(基本类型偏执)

尝试将原本单独存在的数据值替换为对象

Switch Statements(Switch 语句)

大多数时候,一看到 Switch ,就应该考虑使用多态来替换它。

Parallel Inheritance Hierarchies(平行继承体系)

每当你为某个类增加一个子类,也必须为另一个类增加一个子类。消除策略:让一个继承体系的实例引用另一个继承体系的实例。

Lazy Class(冗余类)

删除它。

Speculative Generality(夸夸其谈未来性)

删掉无用的函数和linshi函数中多余的参数。

Temporary Field(令人迷惑的暂时字段)

类中某个实例变量仅为某种特定情况而设置,通常你认为对象在所有时候都需要它的所有变量,在变量未被使用的情况下猜测其设置目的,会让你发疯的!将这些变量抽取为类。

Message Chains(过度耦合的消息链)

用户向一个对象请求另一个对象,然后再向后者请求另一个都西昂,然后再请求另一个对象 ……… 这就是消息链。

Middle Man(中间人)

某个类接口有一半的函数都委托给其他类,这是就应该去掉 Middle Man,直接和真正负责的对象打交道。

Inappropriate Intimacy(狎昵关系)

两个类过于亲密,花费太多时间去探究彼此的 private 成分。应该将这两个类分开,帮它们划清界限。

Alternative Classes with Different Interfaces(异曲同工的类)

两个函数做着同样的事情,却有不同的签名,尝试根据它们的用途进行重命名。

Data Class(纯稚的数据类)

拥有一些字段,以及用于访问这些字段的函数。

Refused Bequest(被拒绝的捐赠)

子类不想或不需要继承超类的函数和数据。

Comments(过多的注释)

一段代码中有长长的注释,尝试重构复杂的地方。

Incomplete Library Class(不完美的库类)

想要对库类添加或修改,可以引入本地扩展。

重新组织函数

Extract Method(提炼函数)

你有一段代码可以被组织在一起并独立出来。将这段代码放进一个独立函数中,并让函数名称解释该函数的用途。

Inline Method(内联函数)

一个函数的本体与名称同样清楚易懂。在函数调用点插入函数本体,然后删除函数。

Inline Temp(内联临时变量)

你有一个临时变量,只被一个简单表达式肤质一次,而它妨碍了其他重构手法。

将所有对该变量的引用动作,替换为对它赋值的表达式自身。

double basePrice = anOrder.basePrice();
return basePrice > 100;
return anOrder.basePrice() > 100;

Return Temp With Query(以查询取代临时变量)

你的此程序以一个临时变量保存某一表达式的运算结果。

将这个表达式提炼到一个独立函数中。将这个临时变量的所有引用点替换为对新函数的调用。此后,新函数就可被其他函数使用。

double basePrice = _quantity * _itemPrice;
if(basePrice > 1000)
    return basePrice * 0.95;
else
    return basePrice * 0.99;
if(basePrice() > 1000)
    return basePrice() * 0.95;
else
    return basePrice() * 0.99;

double basePrice(){
    return _quantity * _itemPrice;
}

Introduce Explaining Variable(引用解释性变量)

你有一个复杂的表达式,将该复杂表达式(或其中一部分)的结果放进一个临时变量,以此变量名称来解释表达式用途。

if((platform.toUpperCase().indexOf('MAC') > -1) &&
  (browser.toUpperCase().indexOf('IE') > -1) &&
  wasInitialized() && resize > 0){
    //do something
}
final boolean isMacOS = platform.toUpperCase().indexOf('MAC') > -1;
final boolean isIEBrowser = browser.toUpperCase().indexOf('IE') > -1;
final boolean wasResized = resize > 0;
if(isMacOS && isIEBrowser && wasInitialized() && wasResized){
// do something}

Split Temporary Variable(分解临时变量)

你的程序有某个临时变量被赋值超过一次,它既不是循环变量,也不被用于收集计算结果。针对每次赋值,创造一个独立、对应的临时变量。

double temp = 2 * (_height + _width);
System.out.println(temp);
temp = _height * _width;
System.out.println(temp);
final double perimeter = 2 * (_height + _width);
System.out.println(perimeter);
final double area = _height * _width;
System.out.println(area);

Remove Assignments to Parameters(移除对参数的赋值)

代码对一个参数进行赋值。以一个临时变量取代该参数的位置

int discount(int inputVal, int quantity, int yearToDate){
    if(inputVal > 50) inputVal -= 2;
}
int discount(int inputVal, int quantity, int yearToDate){
    int result = inputVal;
    if(result > 50) result -= 2;
}

Replace Method with Object(以函数对象取代函数)

你有一个大型函数,其中对局部变量的使用使你无法采用Extract Method

将这个函数放进一个单独对象中,如此一来局部变量就成了对象内的字段。然后你可以在同一个对象中将这个大型函数分解为多个小函数。

class Order{
    //长函数
    double price(){
        double primaryBasePrice;
        double secondaryBasePrice;
        double tertiaryBasePrice;
        // long computation
    }
}
class Order{
    double price(){
        return new PriceCalculator().compute();
    }
}

class PriceCalculator{
    private double primaryBasePrice;
    private double secondaryBasePrice;
    private double tertiaryBasePrice;
    
    double compute(){
        //long computation
    }
}

Subsititute Algorithm(替换算法)

你想要把某个算法替换为另一个更清晰的算法。将函数本体替换为另一个算法。

String foundPerson(String[] people){
    for(int i = 0; i < people.length(); i++){
        if(people[i].equals("Don")){
            return "Don";
        }else if(people[i].equals("John")){
            return "John";
        }else if(people[i].equals("Kent")){
            return "Kent";
        }
    }
    return "";
}
String foundPerson(String[] people){
    List<String> candidates = Arrays.asList(new String[]{"Don", "John", "Kent"});
    for(int i = 0; i < people.length(); i++){
        if(candidates.contains(people[i])){
            return people[i];
        }
    }
    return "";
}

在对象之间搬移特性

Move Method(搬移函数)

你的程序中,有个函数与其驻类之外的另一个类进行更多交流:调用后者,或被后者调用。

在该函数最常引用的类中建立一个有着类似行为的新函数。将旧函数变成一个单独的委托函数,或者将旧函数完全移除。

Move Field(搬移字段)

在你的程序中,某个字段被其所驻类之外的另一个类更多地用到。

在目标类新建一个字段,修改源字段地所有用户,令它们改用新字段。

Extract Class(提炼类)

某个类做了应该由两个类做的事。

建立一个新类,将相关的字段和函数从旧类搬移到新类。

class Person{
    private String name;
    private String officeAreaCode;
    private String officeNumber;
    
    public getTelephoneNumber(){
        return ("(" + officeAreaCode + ")" + officeNumber);
    }
}
class Person{
    private TelephoneNumber tel;
    private String name;
    
    public getTelephoneNumber(){
        return tel.getTelephoneNumber();
    }
}

class TelephoneNumber{
    private String officeAreaCode;
    private String officeNumber;
    
    public getTelephoneNumber(){
        return ("(" + officeAreaCode + ")" + officeNumber);
    }    
}

Inline Class(将类内联化)

某个类没有做太多事情。将这个类的所有特性搬移到另一个类中,然后移除原类。

刚好与Extract Class相反。

Hide Delegate(隐藏“委托关系”)

客户通过一个委托类来调用另一个对象。在服务类上建立客户所需的所有函数,用以隐藏委托关系。

如果某个客户先通过服务对象的字段得到另一个对象,然后调用后者的函数,那么客户就必须知晓这一层委托关系。万一委托关系发生变化,客户也得相应变化。你可以在服务对象上放置一个简单的委托函数,将委托关系隐藏起来,然后去除这种依赖。

class Person{
    private Department department;
    
    public Department getDepartmeent(){
        return department;
    }
}

class Department{
    private String name;
    private Person manager;
    
    public Persion getManager(){
        return manager;
    }
}

如果客户希望知道某人的经理是谁,他必须先取得 Department 对象:

manager = john.getDepartment().getManager();

这样就对客户暴露了 Department 的工作原理,我们在 Person 中建立一个简单的委托函数:

public Person getManager(){
    return department.getManager();
}

然后客户直接调用:

manager = john.getManager();

Remove Middle Man(移除中间人)

某个类做了过多的简单委托动作。让客户直接调用委托类。

Hide Delegate 中这层封装也是有代价的,它的代价就是:每当客户需要使用受托类的新特性时,你就必须在服务端添加一个简单委托函数。随着受托类的特性越来越多,这一过程会让你痛苦不已。这个时候你就应该让客户直接调用受托类。

Introduce Foreign Method(引入外加函数)

你需要为提供服务的类增加一个函数,但你无法修改这个类。在客户类中建立一个函数,并以第一参数形式传入一个服务类实例。

Date newStart = new Date(previousEnd.getYear(), previousEnd.getMonth(), previousEnd.getDate() + 1);
Date new Start = nextDay(previousEnd);

private static Date nextDay(Date arg){
    return new Date(arg.getYear(), arg.getMonth(), arg.getDate() + 1);
}

如果可以修改源码,可以自行添加一个新函数;如果不能,就得在客户端编码,补足你要的那个函数。

如果你发现自己为一个服务类建立了大量外加函数,或者发现有许多类都需要同样的外加函数,就不应该再使用本项重构,而应该使用Introduce Local Extension

Introduce Local Extension(引入本地扩展)

你需要为服务类提供一些额外函数,但你无法修改这个类。

建立一个新类,使它包含这些额外函数。让这个扩展品成为源类的子类或包装类。

我们需要将这些额外函数组织在一起,放到一个恰当地方去。有两种标准对象技术——子类化(subclassing)包装(wrapping)。将子类和包装类统称为本地扩展(Local Extension)。

//子类
class MfDateSub extends Date{
    MfDateSub(String dateString){
        super(dateString);
    }
    
    Date nextDay(){
        return new Date(getYear(), getMonth(), getDate() + 1);
    }
}
//包装类
class MfDateWrap{
    private Date original;
    MfDateWrap(String dateString){
        original = new Date(dateString);
    }
    
    MfDateWrap(Date arg){
        original = arg;
    }
    
    public int getYear(){
        return original.getYear();
    }
    
    public int getMonth(){
        return original.getMonth();
    }
    
    // 省略其他对 Date 类函数的包装
    
    Date nextDay(){
        return new Date(getYear(), getMonth(), getDate() + 1);
    }
}

重新组织数据

Self Encapsulate Field(自封装字段)

你直接访问一个字段,但与字段之间的耦合关系逐渐变得笨拙。为这个字段建立设值/取值函数,并只以这些函数来访问字段。

private int low, high;
boolean includes(int arg){
    return arg >= low && arg <= high;
}
private int low, hign;
boolean includes(int arg){
    return arg >= getLow() && arg <= getHigh();
}

Replace Data Value with Object(以对象取代数据值)

你有一个数据项,需要与其他数据和行为一起使用才有意义。将数据项变成对象。

class Order{
    private String customer;
}
class Order{
    private Customer customer;
}

class Customer{
    private String name;
}

Change Value to Reference(将值对象改为引用对象)

你从一个类衍生出许多彼此相等的实例,希望将它们替换为同一个对象。将这个值对象变成引用对象。

Replace Data Value with Object中,留下了一个重构后的程序。到目前为止,Customer 对象还是值对象。就算多份订单属于同一用户,但每个 Order 对象还是拥有各自的 Customer 对象。我希望一个用户可以有多个订单,所有 Order 对象共同拥有同一个 Customer 对象(每一个客户名称只该对应一个Customer对象)

首先使用Replace Constructor with Factory Method。这样,就可以控制 Customer 对象的创建过程。在 Customer 类中定义这个工厂函数:

class Customer{
    public static Customer create(String name){
        return new Customer(name);
    }
}

然后更改调用点:

class Order{
    public Order(String customer){
        customer = Customer.create(customer);
    }
}

然后把 Customer 类的构造函数改为 private。

在 Customer 类中使用 HashMap 存储 Customer 对象,并更改工厂方法:

class Customer{
    private static Map<String, Customer> instances = new ConcurrentHashMap<>();
    
    private void store(){
        instances.put(this.getName(), this);
    }
    
    //直接写死几个数据(应该从数据库读取)
    static void loadCustomer(){
        new Customer("a").store();
        new Customer("b").store();
        new Customer("c").store();
    }
    
    //工厂方法
    public static Customer getNamed(String name){
        return (Customer) instances.get(name);
    }
}

Change Reference to Value(将引用对象改为值对象)

你有一个引用对象,很小且不可变,而且不易管理。将它变成一个值对象(类没有修改对象数据的函数)。

Replace Array with Object(以对象取代数组)

你有一个数组,其中的元素各自代表不同的东西。以对象替换数组,对于数组中的每个元素,以一个字段来表示。

String[] row = new String[3];
row[0] = "Liverpool";
row[1] = "15";
Performance p = new Performance();
p.setName("Livepool");
p.setWins("15");

Duplicate Observed Data (复制“被监视数据”)

你有一些领域(Model)数据置身于 GUI 控件中,而领域函数需要访问这些函数。

将该数据复制到一个领域对象中。建立一个Observer 模式,用以同步领域对象和 GUI 对象内的重复数据。

Change Unidirectional Association to Bidirectional(将单向关联改为双向关联)

两个类都需要使用对方特性,但其间只有一条单向连接。添加一个反向指针,并使修改函数(指改变双方关系的函数)能够同时更新两条连接。

// 一个用户可以有多个订单
class Order{
    private Customer customer;
    
    void setCustomer(Customer arg){
        if(customer != null)
            customer.friendOrders().remove(this);
        customer = arg;
        if(customer != null)
            customer.friendOrders().add(this);
    }
}

class Customer{
    private Set<Order> orders = new HashSet<>();
    
    Set<Order> friengOrders(){
        return orders;
    }
}

Change Bidirectional Association to Unidirectional (将双向关联改为单向关联)

两个类之间有双向关联,但其中一个类如今不再需要另一个类的特性。去除不必要的关联。

双向关联很有用,但你也为必须为它付出代价,那就是维护双向连接、确保对象被正确创建和删除而增加的复杂度。大量双向连接也容易造成“僵尸对象”:某个对象本来已经死亡了,却仍然保留在系统中,因为对它的引用还没有完全清除。

Replace Magic Number with Symbolic Constant(以字面常量取代魔法数)

你有一个字面数值,带有特别意义。创建一个常量,根据其意义为它命名,并将上述的字面数值替换为这个常量。

double potentialEnergy(double mass, double height){
    return mass * 9.81 * height;
}
static final double GRAVITATIONAL_CONSTANT = 9.81;
double potentialEnergy(double mass, double height){
    return mass * GRAVITATIONAL_CONSTANT * height;
}

Encapsulate Field(封装字段)

你的类中存在一个 public 字段。将它声明为 private,并提供相应的访问函数。

public String name;
private String name;

public String getName(){
    return name;
}
public void setName(String name){
	this.name = name;
}

Encapsulate Collection(封装集合)

有个函数返回一个集合。让这个函数返回该集合的一个只读副本,并在这个类中提供添加/移除集合元素的函数。

class Person{
    List<String> skills = new ArrayList<>();
    String[] getSkills(){
        return (String[])skills.toArray(new String[0]);
    }
    void setSkill(int index, String newSkill){
        skill.set(index, newSkill);
    }
} 

Replace Record with Data Class(以数据类取代记录)

你需要面对传统编程环境中的记录结构。为该记录创建一个 POJO。

Replace Type Code with Class(以类取代类型码)

类之中有一个数值类型码,但它不影响类的行为。以一个新的类替换该数值类型码。

class Person{
    public static int O = 0;
    public static int A = 1;
    public static int B = 2;
    public static int AB = 3;
    privaet int bloodGroup;
}
class Person{
    private BloodGroup bloddGroup;
}

class BloodGroup{
    public static final BloodGroup O = new BloodGroup(0);
    public static final BloodGroup A = new BloodGroup(1);
    public static final BloodGroup B = new BloodGroup(2);
    public static final BloodGroup AB = new BloodGroup(3);
    private static final BloodGroup[] values = {O,A,B,AB};
    
    private final int code;
    
    private BloodGroup(int code){
        this.code = code;
    }
}

Replace Type Code with Subclasses(以子类取代类型码)

你有一个不可变的类型码,它会影响类的行为。以子类取代这个类型码。

class Employee{
    static final int ENGINEER = 0;
    static final int SALESMAN = 1;
    static final int MANAGER = 2;
    private int type;
}
class Engineer extends Employee{
    int getType(){
        return Employee.ENGINEER;
    }
}
//其他两个不写了

Replace Type Code with State/Strategy (以State/Strategy取代类型码)

你有一个类型码,它会影响类的行为,但你无法通过继承手法消除它。以状态对象取代类型码。

继续使用上面的 Employee 例子。

abstract class EmployeeType{
    abstract int getTypeCode();
}
class Employee extends EmployeeType{
    int getTypeCode(){
        return Employee.ENGNIEER;
    }
}
//剩余两个省略
class Employee{
    static final int ENGINEER = 0;
    static final int SALESMAN = 1;
    static final int MANAGER = 2;
    private EmployeeType type;
    
    int getType(){
        return type.getTypeCode();
    }
    
    void setType(int arg){
        switch(arg){
            case ENGNIEER:
                type = new Engineer();break;
            case SALESMAN:
                type = new Salesman();break;
            case MANAGER:
                type = new Manager();break;
            default:
                throw new IllegalArgumentException("Incorrect Employee Code");
        }
    }
}

Replace Subclass with Field(以字段取代子类)

你的各个子类的唯一差别只在“返回常量数据”的函数上。修改这些函数,使它们返回超类中的某个(新增)字段,然后销毁子类。

abstract class Person{
    abstract char getCode();
}

class Male extends Person{
	char getCode(){
        return 'M';
    }
}

class Female extends Person{
	char getCode(){
        return 'F';
    }
}
class Person{
    char code;
    Person(char code){
        this.code = code;
    }
    
    static Person createMale(){
        return new Person('M');
    }
    
    static Person createFemale(){
        return new Person('F');
    }
}

简化条件表达式

Decompose Conditional(分解条件表达式)

你有一个复杂的条件(if - then - else)语句。从 if、then、else 三个段落中分别提炼处独立函数。

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);

Consolidate Conditional Expression(合并条件表达式)

你有一系列条件测试,都得到相同结果。将这些测试合并为一个条件表达式,并将这个条件表达式提炼为一个独立函数。

double disabilityAmount(){
    if(seniority < 2) return 0;
    if(monthsDisabled > 12) return 0;
    if(isPartTime) return 0;
    // compute the disability amount
}
double disabilityAmount(){
    if(isNotEligibleForDisability()) return 0;
    // compute the disability amount
}
boolean isNotEligibleForDisability(){
    return seniority < 2 || monthsDisabled > 12 || isPartTime;
}

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

在条件表达式的每个分支上有着相同的一段代码。将这段重复代码搬移到条件表达式之外。

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();

Remove Control Flag(移除控制标记)

在一系列布尔表达式中,某个变量带有“控制标记(control flag)的作用。以 break 语句或 return 语句取代控制标记。

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

函数中的条件逻辑使人难以看清正常的执行路径。使用卫语句(单独检查语句)表现所有特殊情况。

double getPayAmount(){
    double result;
    if(isDead) result = deadAmount();
    else{
        if(isSeparated) result = separatedAmount();
        else{
            if(isRetired) result = retiredAmount();
            else result = normalPayment();
        }
    }
    return result;
}
double getPayAmount(){
    if(isDead) return deadAmount();
    if(isSeparated) return separatedAmount();
    if(isRetired) return retiredAmount();
    return normalAmount();
}

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

你手上有个条件表达式,它根据对象类型的不同而选择不同的行为。将这个条件表达式的每个分支放进一个子类的覆写函数中,然后将原始函数声明为抽象函数。

double getSpeed(){
    switch(type){
        case EUROPEAN : return getBaseSpeed();
        case AFRICAN: return getBaseSpeed() - getLoadFactor() * numberOfCoconuts;
        case NORWEGIAN_BLUE: return isNailed ? 0 : getBaseSpeed(voltage);
    }
}
abstract class Bird{
    abstract double getSpeed();
}

class European extends Bird{
    double getSpeed(){
        return getSpeed();
}
}
//剩下两个类省略

Introduce Null Object(引入 Null 对象)

你需要再三检查某独享是否为 null。将 null 值替换为 null 对象。

Introduce Assertion(引入断言)

某一段代码需要对程序状态做出某种假设。以断言明确表现这种假设。

断言的失败应该导致一个非受控异常。程序最后的成品往往将断言统统删除。

简化函数调用

Remove Method(函数改名)

函数的名称未能揭示函数的用途。修改函数名称。

Add Parameter(添加参数)

某个函数需要从调用端得到更多信息。为此函数添加一个对象参数,让该对象带进函数所需信息。

Remove Parameter(移除参数)

函数本体不再需要某个参数。将该参数去除。

Separate Query from Modifier(将查询函数和修改函数分离)

某个函数既返回对象状态值,又修改对象状态。建立两个不同的函数,其中一个负责查询,另一个负责修改。

Parameterize Method(令函数携带参数)

若干函数做了类似的工作,但在函数本体中却包含了不同的值。建立单一函数,以参数表达那些不同的值。

class Employee{
    void fivePercentRaise(){...}
    void tenPercentRaise(){...}
}
class Employee{
    void raise(double percentage){...}
}

Replace Parameter with Explicit Methods(以明确函数取代参数)

void setValue(String name, int value){
    if(name.equals("height")){
        height = value;
        return;
    }
    if(name.equals("width")){
        width = value;
        return;
    }
}
void setHeight(int arg){
    height = arg;
}
void setWidth(int arg){
    width = arg;
}

Preserve Whole Object(保持对象完整)

你从某个对象中取出若干值,将它们作为某一次函数调用时的参数。改为传递整个对象。

int low = daysTempRange().getLow();
int high = daysTemoRange().getHigh();
withinPlan = plan.withinRange(low, high);
withinPlan = plan,withinRange(daysTempRange());

Replace Parameter with Methods(以函数取代函数)

对象调用某个函数,并将所得结果作为参数,传递给另一个函数。而接受该参数的函数本身也能调用前一个函数。让参数接受者去除该项参数,并直接调用前一个函数。

int basePrice = quantity * itemPrice;
discountLevel = getDiscountLevel();
double finalPrice = discountedPrice(basePrice, discountLevel);
int basePrice = quantity * itemPrice;
double finalPrice = discountedPrice(basePrice);
// 让 discountedPrice 直接调用 getDiscountLevel 函数

Introduce Parameter Object(引入参数对象)

某些参数总是很自然地同时出现。以一个对象取代这些参数。

class Customer{
    void amountInvoicedIn(Date start, Date end){...}
}
class Customer{
    void amountInvoicedIn(DateRange dateRange){...}
}

Remove Setting Method(移除设值函数)

类中的某个字段应该在对象创建时被设值,然后就不再改变。去掉该字段的所有设值函数。

Hide Method(隐藏函数)

有一个函数,从来没有被其他任何类用到。将这个函数修改为 private。

Replace Constructor with Factory Method(以工厂函数取代构造函数)

你希望在创建对象时不仅仅是做简单的建构动作。将构造函数替换为工厂函数。

Employee(int type){
    this.type = type;
}
static Employee create(int type){
    return new Employee(type);
}

Encapsulate Downcast(封装向下转型)

某个函数返回的对象,需要函数调用者执行向下转型(downcast)。将向下转型动作移到函数中。

Object lastReading(){
    return readings.lastElement();
}
Reading lastReading(){
    return (Reading)readings.lastElement();
}

Replace Error Code with Exception(以异常取代错误码)

某个函数返回一个特定的代码,用以表示某种特殊情况。改用异常。

int withdraw(int amount){
    if(amount > balance){
        return -1;
    }else{
        balance -= amount;
        return 0;
    }
}
void withdraw(int amount) throws BalaceException{
    if(amount > balance) throw new BalanceException();
    balance -= amount;
}

Replace Exception with Test(以测试取代异常)

面对一个调用着可以预先检查的条件,你抛出了一个异常。修改调用者,使它在调用函数之气那先做检查。

double getValueForPeriod(int periodNumber){
    try{
        return value[periodNumber];
    } catch(ArrayIndexOutOfBoundsException e){ // 滥用异常
        return 0;
    }
}
double getValueForPeriod(int periodNumber){
	if(periodNumber >= values.length) return 0;
    return values[periodNumber];
}

处理概括关系(继承关系)

Pull Up Field(字段上移)

两个子类拥有相同的字段。将该字段移至超类。

Pull Up Method(函数上移)

有些函数,在各个子类中产生完全相同的结果。将该函数移至超类。

Pull Up Constructor Body(构造函数本体上移)

你在各个子类中拥有一些构造函数,它们的本体几乎完全一致。在超类中新建一个构造函数,并在子类构造函数中调用它。

class Manager extends Employee{
    Manager(String name, String id, int grade){
        this.name = name;
        this.id = id;
        this.grade = grade;
    }
}
class Manager extends Employee{
    Manager(String name, String id, int grade){
        super(name, id);
        this.grade = grade;
    }
}

Push Down Method(函数下移)

超类中的某个函数只与部分(而非全部)子类有关。将这个函数移到相关的那些子类去。

Push Down Field(字段下移)

超类中的某些字段只被部分(而非全部)子类用到。将这个字段移到需要它的那些子类去。

Extract Subclass(提炼子类)

类中的某些特性只被某些(而非全部)实例用到。新建一个子类,将上面所说的那一部分特性移到子类中。

class JobItem{
    double getTotalPrice(){...}
    double unitPrice(){...}
    Employee getEmployee(){...}
}
class JobItem{
    double getTotalPrice(){...}
    double unitPrice(){...}
}
class LaborItem extends JobItem{
    double unitPrice(){...}
    Employee getEmployee(){...}
}

Extract Superclass(提炼超类)

两个类有相似特性。为这两个类建立一个超类,将相同特性移至超类。

class Department{
    double getTotalAnnualCost(){...}
    String getName(){...}
    int getHeadCount(){...}
}
class Employee{
    double getAnnualCost(){...}
    String getName(){...}
    long getId(){...}
}
abstract class Party{
    protected String name;
    abstract double getAnnualCost();
    abstract String getName();
}

class Employee extends Party{
    double getAnnualCost(){...}
    long getId(){...}
}

class Department{
    double getAnnualCost(){...}
    int getHeadCount(){...}
}

Extract Interface(提炼接口)

若干客户使用类接口中的同一子集,或者两个类的接口有部分相同。将相同的子集提炼到独立接口中。

class Employee{
    String getRate(){...}
    String hasSpecialSkill(){...}
    String getName(){...}
    String getDepartment{...}
}
interface Billable{
    String getRate();
    String hasSpecialSkill();
}
class Employee implements Billable{
    String getRate(){...}
    String hasSpecialSkill(){...}
    String getName(){...}
    String getDepartment{...}
}

Collapse Hierarchy(折叠继承体系)

超类与子类之间无太大区别。将它们合为一体。

Form Template Method(塑造模板函数)

你有一些子类,其中相应的某些函数以相同顺序执行类似的操作,但各个操作的细节上有所不同。

将这些操作分别放金独立函数中,并保持它们都有相同的签名,于是原函数也就变得相同了。然后将原函数上移至超类。

Replace Inheritance with Delegation(以委托取代继承)

某个子类只使用超类接口中的一部分,或是根本不需要继承而来得数据。在子类中新建一个字段用以保存超类;调整子类函数,令它改而委托超类;然后去掉两者之间的继承关系。

Replace Delegation with Inheritance(以继承取代委托)

你在两个类之间使用委托关系,并经常为整个接口编写许多极简单的委托函数。让委托类继承受托类。

大型重构

Tease Apart Inheritance(梳理并分解继承体系)

某个继承体系同时承担两项责任。建立两个继承体系,并通过委托关系让其中一个可以调用另一个。

image-20201016150252385

Convert Procedural Design to Objects(将过程化设计转换为对象设计)

你手上有一些传统过程化风格的代码。将数据记录变成对象,将大块的行为分成小块,并将行为移入相关对象中。

Separate Domain from Presentation(将领域和表述/显示分离)

某些 GUI 类中包含了领域逻辑。将领域逻辑分离出来,为它们建立独立的领域类。

MVC 模式最核心的价值在于:它将用户界面代码(即视图;也是“展示层”)和领域逻辑(即模型)分离了。展现类只含用以处理用户界面的逻辑;领域类不含任何与程序外观的代码,只含业务逻辑相关代码。

Extract Hierarchy(提炼继承体系)

你有某个类做了太多工作,其中一部分工作是以大量条件表达式完成的。建立继承体系,以一个子类表示一种特殊情况。

posted @ 2020-11-25 18:43  hoo334  阅读(214)  评论(0编辑  收藏  举报