Ser*_*rge 1 c++ code-duplication
我最近开始重构一些遗留代码并遇到两个用于绘制坐标网格的函数,问题是这些函数只在它们处理的正交变量上有所不同,就像那样
void DrawScaleX(HDC dc, int step, int x0, int x1, int y0, int y1)
{
for(int x = x0; x < x1; x += step)
{
MoveToEx(dc, x, y0, NULL);
LineTo(dc, x, y1);
}
}
void DrawScaleY(HDC dc, int step, int x0, int x1, int y0, int y1)
{
for(int y = y0; y < y1; y += step)
{
MoveToEx(dc, x0, y, NULL);
LineTo(dc, x1, y);
}
}
Run Code Online (Sandbox Code Playgroud)
因此,如果我决定添加一些奇特的东西,比如抗锯齿,或者只是改变绘图铅笔或者我必须在两者中放置相同的代码并且它的代码重复而且它很糟糕我们都知道原因.
我的问题是你如何将这两个函数重写为一个函数以避免这个问题?
为什么你只是不将for循环的主体提取到一个单独的函数中?然后你可以在提取的函数中做有趣的事情.
void DrawScaleX(HDC dc, int step, int x0, int x1, int y0, int y1)
{
for(int x = x0; x < x1; x += step)
{
DrawScale(dc, x, y0, x, y1);
}
}
void DrawScaleY(HDC dc, int step, int x0, int x1, int y0, int y1)
{
for(int y = y0; y < y1; y += step)
{
DrawScale(dc, x0, y, x1, y);
}
}
private void DrawScale(HDC dc, int x0, int y0, int x1, int y1)
{
//Add funny stuff here
MoveToEx(dc, x0, y0, NULL);
LineTo(dc, x1, y1);
//Add funny stuff here
}
Run Code Online (Sandbox Code Playgroud)