Reputation: 351
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!
Upvotes: 0
Views: 209
Reputation: 18820
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.
Upvotes: 1
Reputation: 24395
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);
}
Upvotes: 0
Reputation: 1494
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);
...
}
Upvotes: 2
Reputation: 19656
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);
....
}
Upvotes: 1
Reputation: 33877
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
}
Upvotes: 1