Polski

Article · Iterator

Iterator: walking a collection without looking inside

The Iterator pattern through orders from a delivery app fetched page by page: the loop in the report knows nothing about pagination, and pages load lazily, only when needed. Generators, yield and iter.Seq in five languages.

By · · 11 min read

Halina's pierogi place also takes orders through a delivery app whose API returns them in pages of 50. The daily report, the VAT export and the courier statistics simply want to "walk through all the orders". Iterator gives them a single for loop and hides the details – pages, cursors, further HTTP requests – inside.

3
pages in the example – only 2 will be fetched
1
loop in the client code – with no knowledge of pagination
5
languages with a built-in protocol – IEnumerable, Iterable, iter.Seq, __iter__, Symbol.iterator

The problem: a loop that knows too much

The first version of the report handled pagination itself:

daily-report-before.ts
async function dailyRevenue(): Promise<number> {
  let page = 1;
  let revenue = 0;
  while (true) {
    const res = await http.get(`/orders?page=${page}&size=50`);
    for (const order of res.data.items) revenue += order.total;
    if (!res.data.hasMore) break; // API v2 switches to cursors: res.headers['x-next-cursor']
    page++;
  }
  return revenue;
}
// ...and the same loop is copied into the VAT export, the courier stats and the loyalty sync

The business logic (summing up revenue) is mixed with the fetching mechanics (page numbers, size, the hasMore flag). The same loop ended up in three other places, so when the API provider switches to cursors, four copies will need fixing. On top of that, the report always fetches everything, even if it only needs the first two large orders.

The solution: separate traversal from the collection

The iterator takes over responsibility for how to traverse. The collection (here: "all orders from the API") exposes a method that returns an iterator, and the iterator offers two operations: "is there a next one?" and "give me the next one". When the current page buffer runs out, the iterator fetches the next page itself. The client sees a flat stream of orders.

Diagram: Lazy page fetching by the iterator
Diagram: Participants of the Iterator pattern
RoleIn the exampleResponsibility
Aggregate (Iterable)AllOrderscreates an iterator; does not expose its structure
IteratorIterator<Order>the interface: next element, end of sequence
Concrete iteratorOrderIterator, a generatorremembers the position, fetches further pages
Clientthe daily reportwalks the elements with a single loop

Implementation in five languages

Java shows a classic external iterator with hasNext()/next(). In C#, TypeScript and Python the same object is generated for us by the compiler or interpreter – a function with yield is enough. Since version 1.23 Go has the iter.Seq type and range over functions. In every variant breaking out of the loop means the third page is never fetched.

Iterator – orders from a paginated API

AllOrders.cs
var api = new FakeOrdersApi();

// Lazy: pages are fetched only while the pipeline needs more orders.
foreach (var order in AllOrders(api).Where(o => o.Total >= 100).Take(2))
    Console.WriteLine($"#{order.Id}: {order.Total} PLN");
// GET /orders?page=1, #2: 120 PLN, GET /orders?page=2, #4: 210 PLN – page 3 is never fetched

static IEnumerable<Order> AllOrders(IOrdersApi api)
{
    for (var number = 1; ; number++)
    {
        var page = api.GetPage(number);
        foreach (var order in page.Items)
            yield return order; // the compiler turns this method into an iterator object
        if (!page.HasMore) yield break;
    }
}

public sealed record Order(int Id, decimal Total);
public sealed record Page(IReadOnlyList<Order> Items, bool HasMore);

public interface IOrdersApi
{
    Page GetPage(int number);
}

public sealed class FakeOrdersApi : IOrdersApi
{
    private readonly Order[][] _pages =
    [
        [new(1, 45m), new(2, 120m)],
        [new(3, 80m), new(4, 210m)],
        [new(5, 150m)],
    ];

    public Page GetPage(int number)
    {
        Console.WriteLine($"GET /orders?page={number}");
        return new Page(_pages[number - 1], number < _pages.Length);
    }
}
all-orders.ts
type Order = { id: number; total: number };
type Page = { items: Order[]; hasMore: boolean };

const pages: Order[][] = [
  [{ id: 1, total: 45 }, { id: 2, total: 120 }],
  [{ id: 3, total: 80 }, { id: 4, total: 210 }],
  [{ id: 5, total: 150 }],
];

function getPage(n: number): Page {
  console.log(`GET /orders?page=${n}`);
  return { items: pages[n - 1], hasMore: n < pages.length };
}

// The collection hides paging; any for...of loop or spread can walk it.
class AllOrders implements Iterable<Order> {
  constructor(private readonly fetch: (n: number) => Page) {}

  *[Symbol.iterator](): Iterator<Order> {
    for (let n = 1; ; n++) {
      const page = this.fetch(n);
      yield* page.items;
      if (!page.hasMore) return;
    }
  }
}

let found = 0;
for (const order of new AllOrders(getPage)) {
  if (order.total < 100) continue;
  console.log(`#${order.id}: ${order.total} PLN`);
  if (++found === 2) break; // break calls return() on the generator – page 3 is never fetched
}

// Under the hood it is the classic protocol: next() returns { value, done }.
const it = new AllOrders(getPage)[Symbol.iterator]();
console.log(it.next()); // { value: { id: 1, total: 45 }, done: false }
AllOrders.java
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.function.IntFunction;

record Order(int id, int total) {}
record Page(List<Order> items, boolean hasMore) {}

// A classic external iterator: the client pulls elements with hasNext()/next().
class OrderIterator implements Iterator<Order> {
    private final IntFunction<Page> api;
    private Iterator<Order> current = List.<Order>of().iterator();
    private int nextPage = 1;
    private boolean more = true;

    OrderIterator(IntFunction<Page> api) { this.api = api; }

    @Override public boolean hasNext() {
        while (!current.hasNext() && more) { // fetch lazily, skipping empty pages
            Page page = api.apply(nextPage++);
            current = page.items().iterator();
            more = page.hasMore();
        }
        return current.hasNext();
    }

    @Override public Order next() {
        if (!hasNext()) throw new NoSuchElementException();
        return current.next();
    }
}

public class AllOrders implements Iterable<Order> {
    private static final List<List<Order>> PAGES = List.of(
        List.of(new Order(1, 45), new Order(2, 120)),
        List.of(new Order(3, 80), new Order(4, 210)),
        List.of(new Order(5, 150)));

    static Page getPage(int n) {
        System.out.println("GET /orders?page=" + n);
        return new Page(PAGES.get(n - 1), n < PAGES.size());
    }

    @Override public Iterator<Order> iterator() { return new OrderIterator(AllOrders::getPage); }

    public static void main(String[] args) {
        int found = 0;
        for (Order o : new AllOrders()) { // for-each works with any Iterable
            if (o.total() < 100) continue;
            System.out.println("#" + o.id() + ": " + o.total() + " PLN");
            if (++found == 2) break; // page 3 is never fetched
        }
    }
}
orders.go
package main

import (
	"fmt"
	"iter"
)

type Order struct{ ID, Total int }

type Page struct {
	Items   []Order
	HasMore bool
}

var pages = [][]Order{{{1, 45}, {2, 120}}, {{3, 80}, {4, 210}}, {{5, 150}}}

func getPage(n int) Page {
	fmt.Printf("GET /orders?page=%d\n", n)
	return Page{pages[n-1], n < len(pages)}
}

// AllOrders returns a lazy sequence (Go 1.23+); it stops as soon as yield returns false.
func AllOrders(fetch func(int) Page) iter.Seq[Order] {
	return func(yield func(Order) bool) {
		for n := 1; ; n++ {
			page := fetch(n)
			for _, o := range page.Items {
				if !yield(o) {
					return
				}
			}
			if !page.HasMore {
				return
			}
		}
	}
}

func main() {
	found := 0
	for o := range AllOrders(getPage) {
		if o.Total < 100 {
			continue
		}
		fmt.Printf("#%d: %d PLN\n", o.ID, o.Total)
		found++
		if found == 2 {
			break // yield returns false – page 3 is never fetched
		}
	}
}
all_orders.py
from dataclasses import dataclass
from itertools import islice
from typing import Callable, Iterator


@dataclass(frozen=True)
class Order:
    id: int
    total: int


@dataclass(frozen=True)
class Page:
    items: list[Order]
    has_more: bool


PAGES = [[Order(1, 45), Order(2, 120)], [Order(3, 80), Order(4, 210)], [Order(5, 150)]]


def get_page(n: int) -> Page:
    print(f"GET /orders?page={n}")
    return Page(PAGES[n - 1], n < len(PAGES))


def all_orders(fetch: Callable[[int], Page]) -> Iterator[Order]:
    """A generator is an iterator: it hides paging and fetches pages lazily."""
    n = 1
    while True:
        page = fetch(n)
        yield from page.items
        if not page.has_more:
            return
        n += 1


big_orders = (o for o in all_orders(get_page) if o.total >= 100)
for order in islice(big_orders, 2):  # take two – page 3 is never fetched
    print(f"#{order.id}: {order.total} PLN")

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • External and internal iterators
  • Laziness, pipelines and pitfalls
  • When to use it and when not to
  • Related patterns
  • In practice
  • Test yourself

Create a free account · Sign in