如何在不转向布尔开关参数的情况下避免代码重复?

时间:2016-12-14 09:31:11

标签: java

我刚刚找到以下代码:

public ThingId foo1(Map<String, Object> properties) {
  checkSomething();
  validateA(properties);
  validateB(properties);
  ...
  validateX(properties);
  return createTheThing(properties);
}

public ThingId foo2(Map<String, Object> properties, MoreStuff stuff) {
  checkSomething();
  validateB(properties);
  ...
  validateX(properties);
  return createTheThing(properties, stuff);
}

所以这两个方法体几乎完全相同,除了foo2()没有调用validateA()

尝试减少代码重复,我转向

private void checkAndValidate(Map<String, Object> properties, booelean validateA) {
  checkSomething();
  if (validateA) {
    validateA();
  }
  validateB(properties);
  ...
  validateX(properties);
}

因此foo1()foo2()都可以使用该新方法。但我真的不喜欢那里的布尔参数。

任何想法,任何人?

2 个答案:

答案 0 :(得分:2)

您可以将验证放在新方法中:

private void foo3(Map<String, Object> properties) {
  validateB(properties);
  ...
  validateX(properties);    
}


public ThingId foo1(Map<String, Object> properties) {
  checkSomething();
  validateA(properties);
  foo3(properties);
  return createTheThing(properties);

}

public ThingId foo2(Map<String, Object> properties,MoreStuff stuff) {
  checkSomething();
  foo3(properties);
  return createTheThing(properties,stuff);
}

答案 1 :(得分:2)

好问题!我也很想知道这件事。 下面是我通常做的,不是最好的,但可以使用布尔参数减少半倍的调用方法。

PHPUnit_Framework_Error_Notice