如何重构这些方法以避免重复?

时间:2011-11-01 07:32:41

标签: c# .net refactoring

在我们的代码库中

public ActionResult Copy(string id, string targetId)
            {
                //lot of similar code
                Copy(sourcePageRef, destinationPageRef);
                //lot of similar code
            }

public ActionResult Move(string id, string targetId)
        {
            //lot of similar code
            Move(sourcePageRef, destinationPageRef);
            //lot of similar code
        }

问题是,复制和移动有不同的签名:

PageRef Copy(PageRef, PageRef)

void Move(PageRef, PageRef)

如何重构这些方法以避免重复? 谢谢

4 个答案:

答案 0 :(得分:7)

如果您不需要Copy的结果,您仍然可以使用Action<string, string>或任何类型:

public ActionResult Copy(string id, string targetId)
{
    CopyOrMove((x, y) => Copy(x, y));
}

public ActionResult Move(string id, string targetId)
{
    CopyOrMove(id, targetId, (x, y) => Move(x, y));
}

private void CopyOrMove(string id, string targetId,
                        Action<string, string> fileAction)
{
    // lot of similar code
    fileAction(sourcePageRef, destinationPageRef);
    // lot of similar code
}

那是一个选项。这取决于“很多类似代码”实际上在做什么,以及第二个块是否需要第一个块的结果。例如,如果您可以这样做:

public ActionResult Copy(string id, string targetId)
{
    string sourcePageRef = PrepareSourceFile(id, targetId);
    string targetPageRef = PrepareTargetFile(targetId);
    Copy(sourcePageRef, targetPageRef);
    CleanUp(sourcePageRef, targetPageRef);
    return ...;
}

public ActionResult Move(string id, string targetId)
{
    string sourcePageRef = PrepareSourceFile(id, targetId);
    string targetPageRef = PrepareTargetFile(targetId);
    Move(sourcePageRef, targetPageRef);
    CleanUp(sourcePageRef, targetPageRef);
    return ...;
}

...那么这可能比重构与委托方法更简单。

答案 1 :(得分:0)

我不会重构这些方法,但是如果可能的话,将这些方法的内容放入单独的私有函数中,在一种情况下移动数据,在另一个Copies中。所以你提供的方法可以使用它。从方法名称中可以清楚地知道它的作用,不要改变它恕我直言,考虑到它们是公开的并且对你的班级消费者也是可见的。

答案 2 :(得分:0)

提取这些:

  

//很多相似的代码

到他们自己的方法,只需从你的Move或Copy方法中调用它们。

答案 3 :(得分:0)

我看到两个选项: 选项A)使用decompose方法提取公共代码,并从每个重复方法中编写代码类:

  Copy(,) {
    CommonCodeA();
    Copy(..);
    CommonCodeB();
  }

  Move(,) {
    CommonCodeA();
    Move(..);
    CommonCodeB();
  }

  CommonCodeA() {...}

  CommonCodeB() {...}

选项B)使用模板方法重构:将公共代码放在超类方法中,并使此方法调用特定代码的抽象方法。然后为每个重复的方法创建一个子类,实现抽象方法。

 class OperationAction {

      operation() {
           //lots of code
           do(,);
           //lots of code
      }
      abstract do();
 }

 class CopyAction extends OperationAction {
     do() {
          Copy(srcref,destref);
     }
     Copy(srcref,destref) { ... }
 }

 class MoveAction extends OperationAction {
     do() {
          Move(srcref,destref);
     }
     Move(srcref,destref) { ... }
 }