如何处理具有不同参数的相同代码路径?
我遇到过一种情况,尝试不必修改底层源代码(它在该级别上并不是真正的“我的”代码;否则,我很想修改它),我有两个几乎相同的代码路径,但是我正在使用的不同类型的数据。
忽略您可能可以相当容易地将一个对象转换为另一个对象,类似的示例将是一个“Circle”对象。
一方面,我有一个 Point 对象和一个半径。另一方面,我有一个 Circle 对象。这两者都可以描述相同的实际圆,但我无法将其转换为另一个。
然后,在我的代码中,我有:
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) { /* ... */ }
当然,我在 Run
中的代码比本示例中的代码多。
如何将 Run
合并到单个函数中以最大程度地减少代码重复?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在这种情况下,您可以采取两条路径:
不相关
部分中计算圆的直径(无论是否真实),请创建一个方法calcDiameter(radius)
。在这种情况下,如果只有几行代码确实无法使新方法变得实用,那么重复的代码并没有本质上的错误。
There are two paths you could take in this case:
unrelated
section you calculate the diameter of the circle (realistic or not), create a methodcalcDiameter(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.
一个泛型的例子:
An example with generics:
至少,您可以在单独的方法中执行
不相关的操作
,并从每个Run
中调用它。At a minimum, you could do your
unrelated stuff
in a separate method and call it from eachRun
.您可以为它们创建一个公共接口,如下所示:
然后您只需要一种接受 IMyShape 引用的方法:
You could create a common interface for the both of them that would look something like this:
Then you would only need one method that accepted an IMyShape reference: