如何避免代码重复?

时间:2012-05-23 10:14:20

标签: c# oop code-duplication overloading duplication

我在类中有两种方法,一种带有额外的参数

第一个:

public override void CalcV(IV iv)
{
     initializations
     otherOperations

     for (int i=0; i < NUM; ++i)
     {
         SomeOtherOperations
         double v = GetV(a,b,c);
         SomeOtherOperationsUsing_v
     }

     restOfOperations
}

和第二个:

public override void CalcV(IV iv, int index)
{
     initializations
     otherOperations

     for (int i=0; i < NUM; ++i)
     {
         SomeOtherOperations
         double v = GetV(a,b,c, index);
         SomeOtherOperationsUsing_v
     }

     restOfOperations
}

你可以看到唯一的区别是第一个用3个参数调用GetV(),第二个用4个参数调用GetV()的重载。

我最好能避免代码重复吗?

谢谢!

5 个答案:

答案 0 :(得分:2)

假设您不知道合理的默认值,一种非常简单的方法是:

public override void CalcV(IV iv)
{
    CalcV(iv, null);
}

public override void CalcV(IV iv, int? index)
{
     ...
     double v = index.HasValue ? GetV(a,b,c,index.Value) : GetV(a,b,c);
     ...
}

答案 1 :(得分:1)

猜测GetV的作用(你需要改变它以适应:

public override void CalcV(IV iv)
{
     CalcV(iv, 0);
}


public override void CalcV(IV iv, int index)
{
     initializations
     otherOperations

     for (int i=0; i < NUM; ++i)
     {
         SomeOtherOperations
         double v = GetV(a,b,c, index);
         SomeOtherOperationsUsing_v
     }

     restOfOperations
}

答案 2 :(得分:1)

如果您使用的是.Net 4.0,则可以将其设为可选参数:

public override void CalcV(IV iv, int index = -1)
{
    ....
    double v = index > -1 ? GetV(a,b,c, index) : GetV(a,b,c);

    ....
}

答案 3 :(得分:1)

public override void CalcV(IV iv, int? index = null)
{
     initializations
     otherOperations

     for (int i=0; i < NUM; ++i)
     {
         SomeOtherOperations
         double v = index != null ? GetV(a,b,c, index) : GetV(a,b,c);
         SomeOtherOperationsUsing_v
     }

     restOfOperations
}

然后你可以删除第一个覆盖,这将处理两种情况。

答案 4 :(得分:0)

我认为index基于0且为正:

public override void CalcV(IV iv, int index)
{
  initializations
  otherOperations

  for (int i=0; i < NUM; ++i)
  {
    SomeOtherOperations
    double v = index == -1 ? GetV(a, b, c) : GetV(a,b,c, index);
    SomeOtherOperationsUsing_v
  }

  restOfOperations
}

然后,如果要使用四个参数调用GetV,则调用索引为-1的函数,以便使用带有三个参数的GetV或“正确”索引。

public override void CalcV(IV iv)
{
  return CalcV(iv, -1);
}