这是重用/共享方法的好方法吗?

Car*_*eon 5 java refactoring

我遇到了这样的代码,其中3个控制器正在使用方法调用,例如ClassA.search(a,b,flag).这是该方法的简化版本:

public List<Result> search(Object a, Object b, boolean flag) {
   //do some code logic here, common to the 3 controllers
   //at the middle there is:
   if (flag) {
      //code that affects 2 Controllers
   } else {
      //code affects only 1
   }
   //some more common code
   //some more code with the flag if else
}
Run Code Online (Sandbox Code Playgroud)

这是一个好主意,因为代码被重用了吗?或者是否有更好的方法仍然能够进行代码重用,但没有为方法调用(客户端)代码定制引入此标志(比如可能将其拆分为3种不同的方法,但仍然能够声明公共代码重构方法)?

Tom*_*icz 6

首先,提取带有函数的注释行:

public void search(Object a, Object b, boolean flag)
{
    commonToThree();
    if (flag)
    {
        affectTwoControllers();
    }
    else
    {
        affectsOnlyOne();
    }
    alsoCommon();
}
Run Code Online (Sandbox Code Playgroud)

现在摆脱flag布尔参数,这是一个代码气味:

public void searchWithTrueFlag(Object a, Object b) {
    commonToThree();
    affectTwoControllers();
    alsoCommon();
}

public void searchWithFalseFlag(Object a, Object b) {
    commonToThree();
    affectsOnlyOne();
    alsoCommon();
}
Run Code Online (Sandbox Code Playgroud)