【问题标题】:Can I avoid code duplication when the return type is different?当返回类型不同时,我可以避免代码重复吗?
【发布时间】:2016-09-12 09:43:39
【问题描述】:

我有两种逻辑完全相同的方法:

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 是为了强调没有简单的方法可以在两者之间进行转换。

【问题讨论】:

  • 所以你的员工是狗? ;)
  • 如果逻辑完全相同,您可以创建一个附加方法并在RunDog()RunEmployee() 中调用它以避免冗余。
  • 好吧,也许可以将您的业务逻辑与您的 Run 方法分离,看看您是否可以使用它来启动您的狗和员工?如果您有 RunDog 和 RunEmployee 的 2 个实用方法,但您的业务逻辑是相同的,那么您就可以了。如果您的狗和员工共享一个基接口或父类,这会变得容易得多,因为您可以将其添加到泛型类型中作为限制,例如 where T: IBaseDataType 或类似的东西
  • @ThiefMaster - 没有 Shmoopy 只会像狗一样工作!! :P

标签: c# code-duplication


【解决方案1】:

如果这两种方法返回不同的类型,那么它们会做不同的事情,尽管它们在内部使用相同的业务逻辑。所以我会提取常用的业务逻辑,如

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
    }
}

【讨论】:

    【解决方案2】:

    您可以将方法/动作作为参数传递:

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

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

    【讨论】:

      【解决方案3】:

      也许您的建模系统有问题...

      如果您有两个不同的类在一个或多个元素上共享相同的行为(或逻辑),那么它们的共同点应该在基类中或通过接口表达。

      假设你想让它们运行,创建一个接口 IRunner

      interface IRunner
      {
          IRunner runMethod(runnerParam);
      }
      

      所以如果你的两个类都实现了这个类,你就执行一次逻辑:

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

      【讨论】:

        猜你喜欢
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多