2009年4月27日星期一

面向接口编程

在类A中发现如下代码:

public TestStepExecuteResult deviceCommand(final String command,
final Vector inputParams, final Vector outputParams) {
... ...
AbcCommandExecutor executor = AbcExecutorSessions.getInstance()
.getExecutor(AbcExecutorType.CASE_EXECUTOR);
if (command.equals("TspStatusCheck")) {
testStep = new TspSysStatusCheck();
return (testStep.testStepRun(inputParams, outputParams, executor));
} else if (command.equals("TspCreateVlan")) {
testStep = new TspVlanCreateVLAN();
return (testStep.testStepRun(inputParams, outputParams, executor));
} else if (command.equals("TspCreateDhcpProvider")) {
testStep = new TspDhcpCreateDhcpProvider();
return (testStep.testStepRun(inputParams, outputParams, executor));
} else if .....
.....// 省略n多行。
} else {... ...
}
....
}

显然,可以重构,很简单。
  1. 找到testStep对应的父类或接口,假如是ITestStep。
  2. 修改deviceCommand()签名,
    public TestStepExecuteResult deviceCommand(ITestStep testStep,
    final Vector inputParams, final Vector outputParams) 。
  3. 把诸如 new TspSysStatusCheck() 的代码,移到方法调用前的某个合适位置(也许需要利用反射)。
  4. 修改臭味部分,把n多行的if-else if -else if替换为一行:
    return testStep.testStepRun(inputParams, outputParams, executor);

实际上,inputParams, outputParams也是可以/应该放到ITestStep中的。因为,本来这些数据的属主也是ITestStep。

没有评论:

发表评论