3 Replace Parameter with Explicit Method(以明确函数取代参数)
如果某个参数有多种可能的值,而函数内又以条件表达式检查这些参数值,并根据不同参数值作出不同的行为,那么就可以使用Replace Parameter with Explicit Method进行重构了。该手法是提供了不同的函数给调用者使用,避免出现条件表达式。
重构示例20
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// 重构前 static Employee* Create(int type) { switch (type) { case ENGINEER: return new Engineer; case SALESMAN: return new Salesman; case MANAGER: return new Manager; default: return nullptr; } }
1 2 3 4 5 6 7 8 9 10 11 12 13
// 重构后 static Employee* CreateEngineer() { return new Engineer; } static Employee* CreateSalesman() { return new Salesman; } static Employee* CreateManager() { return new Manager; }