I've encountered a situation where, trying not to have to modify the underlying source (it's not really "my" code at that level; otherwise, I'd love to modify it), I have two almost identical code paths, but with separate types of data I'm using.
Ignoring that you could probably convert one to the other rather easily, a similar example would be a "Circle" object.
On one hand, I have a Point
object and a radius. On the other, I have a Circle
object. Both of these can describe the same actual circle, but I just can't convert one to another.
Then, in my code, I have:
void Run(Circle circle)
{
if(AllNegative(circle))
{
// ...
// Do unrelated stuff
// ...
ColorCircle(circle);
// ...
}
}
void Run(Point pt, uint radius)
{
if(AllNegative(pt, radius))
{
// ...
// Do unrelated stuff
// ...
ColorCircle(pt, radius);
// ...
}
}
bool AllNegative(Circle circle) { return (circle.AllNegative); }
bool AllNegative(Point pt, uint radius) { return ((pt.X + radius) < 0) && ((pt.Y + radius) < 0); }
void ColorCircle(Circle circle) { /* ... */ }
void ColorCircle(Point pt, uint radius) { /* ... */ }
Of course, I have more code in Run
than in this example.
How do I merge Run
into a single function in order to minimize code duplication?
There are two paths you could take in this case:
unrelated
section you calculate the diameter of the circle (realistic or not), create a method calcDiameter(radius)
.There's nothing inherantly wrong with duplicated code in this sort of situation, if it's only a couple of lines that really don't make a new method practical.