How do you follow DRY with code with xy coords?

How would you choose the perfect DRY in this example in your chosen language:

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));
}

Note. Many special preprocessor macros are likely to be extremely less readable and writable, so outside of it.

+3
source share
4 answers

The answer is simple: vectors. For example.

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);
+9
source

[I agree with Stuart, but I insist on an academic exercise.]

Tricky ...

In a way, you are not repeating yourself; you do two similar things that are (literally and figuratively) orthogonal to each other.

I assume that you could do the following, although it was not more readable and, of course, more inefficient:

[pseudo #]:

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);
}

-, , ...: -)

+1

, DRY ?

, , , - , , , - !

0

If your grid is square, I think the following might work:

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));
}
0
source

Source: https://habr.com/ru/post/1703570/


All Articles