Question

I have two flavours of a method in a class, one with an extra parameter

first one:

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
}

and second one:

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
}

as you can see the only difference is that the first one calls GetV() with 3 parameters and the second one calls an overload of GetV() with 4 parameters.

How best I can avoid code duplication here?

Thanks!

Was it helpful?

Solution

If you're using .Net 4.0, you can make it an optional parameter:

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

    ....
}

OTHER TIPS

Assuming you don't know a reasonable default, a very simple way would be:

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);
     ...
}

Having a guess at what GetV does (you'll need to change this to suit:

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

Then you can remove the first override and this will deal with both scenarios.

I assume index is 0-based and positive:

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
}

Then you call the function with the index of -1 of you want to use GetV with three parameters or a "correct" index if you want to call GetV with four parameters.

public override void CalcV(IV iv)
{
  return CalcV(iv, -1);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top