3

您将如何以您选择的语言在此示例中获得梦寐以求的 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));
}

注意:大量的 ad-hoc 预处理器宏的可读性和可写性可能极低,因此已淘汰。

4

4 回答 4

9

答案很简单:向量。例如

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);
于 2009-02-20T14:52:59.410 回答
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);
}

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

于 2009-02-20T14:45:03.237 回答
0

也许,在这种情况下,你把 DRY 太过分了?

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

于 2009-02-20T14:33:38.663 回答
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));
}
于 2009-02-20T15:02:17.453 回答