簡體   English   中英

返回類型不同時,可以避免代碼重復嗎?

[英]Can I avoid code duplication when the return type is different?

我有兩種邏輯完全相同的方法:

Dog RunDog()
{
    // a LOT of businees logic
    return DogMethod(dogParams);
}

Employee RunEmployee()
{
    // the exact same logic from above
    return EmployeeMethod(employeeParams (can be easily converted to/from dogParams));
}

有沒有一種通用的設計模式可以幫助我避免代碼重復?

也許像這樣:

T RunT()
{
    // Logic...
    // Invoke DogMethod/EmployeeMethod depending on T and construct the params accodringly
}

我選擇了Dog / Employee,以強調在這兩者之間沒有簡單的轉換方法。

如果這兩種方法返回不同的類型,那么盡管它們在內部使用相同的業務邏輯,但它們會執行不同的操作。 因此,我將提取常用的業務邏輯,例如

class Running
{
    public Dog RunDog()
    {
        var dogParams = GetParams();
        return DogMethod(dogParams);
    }

    public Employee RunEmployee()
    {
        var dogParams = GetParams();
        var employeeParams = ConvertParams(dogParams);
        return EmployeeMethod(employeeParams);
    }

    private DogParams GetParams()
    {
          // a LOT of business logic
    }
}

您可以將方法/操作作為參數傳遞:

T RunT<T>(Func<T> function){
    return function()
}

有關更多信息: https : //simpleprogrammer.com/2010/09/24/explaining-what-action-and-func-are/

也許您的建模系統有問題...

如果您有兩個不同的類在一個或多個元素上共享相同的行為(或邏輯),則它們的共同點應該在基類中或通過接口表示。

假設您想讓它們運行,創建接口IRunner

interface IRunner
{
    IRunner runMethod(runnerParam);
}

因此,如果兩個類都實現了該類,則只需執行一次邏輯:

IRunner Run()
{
    //Your logic here
    return myRunner.runMethod(runnerParam);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM