1

For example, if there's multiple lines to be drawn, I could do

function drawLines(lines) {
    lines.forEach(function (line) {
        drawLine(line);
    });
}
function drawLine(line) {
    //...
}

and then in the "main" section of the code I would merely have to call drawLines(lines) rather than writing a forEach there.

This does prevent the need for multiple forEach's to be written if there's more than one section of code that needs to render some lines. I'd only need to call drawLines(lines) in any such place. But at the same time, it just feels like a bit of a silly thing to do.

(The lines thing is just an example... I'm just talking about the general concept of "do something with each item in an array").

clb
  • 521

2 Answers2

1

This is actually a good question, and somewhat subtle. I assume your style is object oriented? If you are using functional or imperative, the answer would be different.

An array have no further semantics than being a collection of items, so clients should treat it as that, i.e. use collection operations like forEach.

But the question is if the lines should be passed around as an array in the first place. Since you are tempted to write a method drawLines() which treat the array of lines as a whole, it indicates you should consider encapsulating the array of lines in a distinct Figure object. You would have a Figure.draw() method, which internally would call drawLine() (or preferably line.draw()) on each line.

JacquesB
  • 61,955
  • 21
  • 135
  • 189
1

If it's more than a line of two lines I would do it that way. Drawing a single line is easy but drawing in general can involve a bunch of steps and can be confusing for the next person that comes along, for that reason I would generally put drawing logic in a method like this. It kind of has to do with theme and making into bite sized chunks. Drawing uses different concepts to loops and data structures and separating drawing means the person looking at it only needs to think about drawing and then they are looking at the loop they only need to understand that drawing gets done.