重构读书笔记-10_6-Replace_Parameter_wi

2019-07-20  本文已影响0人  MR_Model

重构第十章

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

你有一个函数,其内完全取决于参数值而采取不同反应。针对该参数的每一个可能值,建立一个独立函数。

Example:

static final int ENGINEER = 0;
static final int SALESMAN = 1;
static final int MANAGER = 2;
static Employee create(int type) {
    switch (type) {
        case ENGINEER:
            return new Engineer();
        case SALESMAN:
            return new Salesman();
        case MANAGER:
            return new Manager();
        default:
            throw new IllegalArgumentException(*Incurrect type code value);
    }
}

End:

static Employee createEngineer() {
    return new Engineer();
}
static Employee createSalesman() {
    return new Salesman();
}
static Employee createManager() {
    return new Manager();
}
//调用由
Employee kent = Employee.create(ENGINEER)
//替换为
Emplouee kent = Employee.createEngineer();

Conclusion:

Replace Parameter with Explicit Methods(以明确函数取代参数)和Paraneteruze Method(令函数携带参数)恰恰相反。使用本项重构手法的情景在于,程序内部以条件式检查参数值,并根据不同的参数值做出不同的反应。
这样首先可以得到[编译器代码校验的作用],而且接口更加的清楚。
但是,如果参数值不会对函数行为有太多的影响,就不应该使用Replace Parameter with Explicit Methods(以明确函数取代参数)方法。

注意

重构必须在有单元测试的情况下,保证之前的功能修改后不收影响。切记!!!
上一篇 下一篇

猜你喜欢

热点阅读