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

Vim*_*987 1 .net c# refactoring

在我们的代码库中

public ActionResult Copy(string id, string targetId)
            {
                //lot of similar code
                Copy(sourcePageRef, destinationPageRef);
                //lot of similar code
            }
Run Code Online (Sandbox Code Playgroud)

public ActionResult Move(string id, string targetId)
        {
            //lot of similar code
            Move(sourcePageRef, destinationPageRef);
            //lot of similar code
        }
Run Code Online (Sandbox Code Playgroud)

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

PageRef Copy(PageRef, PageRef)
Run Code Online (Sandbox Code Playgroud)

void Move(PageRef, PageRef)
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*eet 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
}
Run Code Online (Sandbox Code Playgroud)

这是一个选择.这取决于"很多类似代码"实际上在做什么,以及第二个块是否需要第一个块的结果.例如,如果你可以这样做:

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 ...;
}
Run Code Online (Sandbox Code Playgroud)

...那么这可能比重构代表方法更简单.