Suppose I have a class Point
and a function to process Point
instances
class Point { private final int x, y; ... } ... void handlePoints(Iterable<Point> points) { for (Point p: points) {...} }
Now I would like to read points
from a file. Each line of the file contains two numbers, so I have a function ("factory method") to create a point
from a line.
Point makePoint(String line) { ... }
What should I do now? I can write a function to read the file to a list of points
and call the handlePoints
function.
List<Point> readPoints(BufferedReader reader) {...} // use makePoint here void handlePoints(BufferedReader reader) { List<Point> points = readPoints(reader); handlePoints(points); }
Unfortunately this function does not seem particularly elegant since it creates an unnecessary list of points in memory.
Wouldn't it be better to use iterators ?
void handlePoints(Iterator<Point> points) {...} Iterator<Point> readPoints(BufferedReader reader) {...} // use makePoint here void handlePoints(BufferedReader reader) { Iterator<Point> points = readPoints(reader); handlePoints(points); }
Does it make sense? Won't be this code too "noisy" in Java?