你如何使用x-y coords跟踪DRY代码?

时间:2009-02-20 14:22:09

标签: dry coordinates

您将如何以您选择的语言在此示例中获得梦想的DRY理想:

drawLine(Point(0, 0), Point(w, 0));
int curRowY = 0;
for(int row=0; row<rowHeights.size(); row++) {
    curRowY += rowHeights[row];
    drawLine(Point(0, curRowY), Point(w, curRowY));
}

drawLine(Point(0, 0), Point(0, h));
int curColX = 0;
for(int col=0; col<colWidths.size(); col++) {
    curColX += colWidths[col];
    drawLine(Point(curColX, 0), Point(curColX, h));
}

注意:大量的临时预处理器宏可能非常 可读和可写,因此无法使用。

4 个答案:

答案 0 :(得分:9)

答案很简单:矢量。 E.g。

repeatLines(Point start, Point end, Vector direction, int[] gaps)
    {
    drawLine(start, end);
    for (int i = 0; i < gaps.Length; i++)
        {
        Vector vector = direction * gaps[i];
        start += vector;
        end += vector;
        drawLine(start, end);
        }
    }

repeatLines(Point(0, 0), Point(0, w), Vector(1, 0), rowHeights);
repeatLines(Point(0, 0), Point(h, 0), Vector(0, 1), colWidths);

答案 1 :(得分:1)

[我同意斯图尔特的观点,但我继续作为学术演习。]

...刁钻

在某种程度上,你不是真的重复自己;你正在做两个相似的事情(字面上和比喻上)彼此正交。

我想你可以做到以下几点,虽然它不再具有可读性,当然也没有更高的性能:

[伪C#]:

void DrawGrid()
{
    DrawLines(w, rowHeights, true);
    DrawLines(h, colWidths, false);
}

void DrawLines(int lineLength, int[] lineSeparations, bool isHorizontal)
{
    MyDrawLine(Point(0, 0), Point(lineLength, 0), isHorizontal);
    int offset = 0;
    for (int i = 0; i < widths.length; i++)
    {
        offset  += lineSeparations[i];
        MyDrawLine(Point(offset, 0), Point(offset, lineLength), isHorizontal);
    }
}

void MyDrawLine(Point startPoint, Point endPoint, bool isHorizontal)
{
    if (isHorizontal)
    {
        SwapXAndYCoordinates(startPoint);
        SwapXAndYCoordinates(endPoint);
    }

    drawLine(startPoint, endPoint);
}

再想一想,我认为这只是一个愚蠢的想法......: - )

答案 2 :(得分:0)

也许,在这种情况下,你将DRY带到了极端的极端?

尽管如此,作为一项学术活动,我期待看到是否有人能够提出与您当前代码一样可读的解决方案 - 但没有明显的重复!

答案 3 :(得分:0)

如果您的网格是方形的,我认为以下方法可行:

void drawGrid()
{
    for(int i = 1, offset = 10; i <= numPoints; i++, offset += 10)
    {
        Point p = new Point(i * offset, i * offset);

        drawHorizontal(p);
        drawVertical(p);
    }
}

void drawHorizontal(Point p)
{
    drawLine(new Point(0, p.y), new Point(width, p.y));
}

void drawVertical(Point p)
{
    drawLine(new Point(p.x, 0), new Point(p.x, height));
}