Design Patterns

Pattern 15 of 23, Behavioral family

Iterator

Also known as: Cursor

Traverse the elements of a collection without exposing its internal representation (list, tree, paginated API…).

The problem

An API returns users in pages of 100. Every piece of client code has to deal with page numbers, buffers and the stop condition: pagination logic leaks everywhere.

The solution

Encapsulate the traversal in an iterator (next() / hasNext() or a generator). The client writes a plain for loop; the iterator loads pages on demand.

The pattern in action

  • Client
  • Key role of the pattern
  • Object
  • Data or state
  1. The client asks for the next element, nothing more.
  2. Empty buffer: the iterator loads a page.
  3. API /users → UserIterator [ ]: [u1, u2, u3]
  4. UserIterator [u1, u2, u3] → Client (for…of): u1
  5. Client (for…of) → UserIterator [u2, u3]: next()
  6. Served from the buffer, with no network call.
  7. Client (for…of) → UserIterator [u3]: next()
  8. UserIterator [u3] → Client (for…of): u3
  9. Client (for…of) → UserIterator [ ]: next()
  10. Buffer exhausted: next page. The client never saw the pagination.

An analogy

The "next channel" button on a remote control: you move forward without knowing the internal list of frequencies.

When to use it

  • Complex collections (trees, graphs)
  • Pagination, streaming, database cursors
  • Lazy traversal of large data sets

Pros and cons

Pros

  • The client knows nothing about the internal structure
  • Several traversals can run at the same time
  • Lazy evaluation → memory under control

Cons

  • Overkill for a plain list
  • Handling network errors in the middle of an iteration

Implementations

The same example, written idiomatically in each language.

Iterator in Python

iterator.py 16 lines
from collections.abc import Iterator


def users(api) -> Iterator[dict]:
    """Generator: iterates over all pages transparently."""
    page = 1
    while True:
        batch = api.get("/users", page=page)
        if not batch:
            return
        yield from batch
        page += 1


for user in users(api):          # the client is unaware of pagination
    print(user["email"])

Iterator in TypeScript

iterator.ts 11 lines
async function* users(api: Api): AsyncGenerator<User> {
  for (let page = 1; ; page++) {
    const batch = await api.get<User[]>("/users?page=" + page);
    if (batch.length === 0) return;
    yield* batch;
  }
}

for await (const u of users(api)) {
  console.log(u.email); // pagination is invisible to the client
}

Iterator in Java

iterator.java 22 lines
class UserIterator implements Iterator<User> {
    private final Api api;
    private int page = 1;
    private Deque<User> buffer = new ArrayDeque<>();

    UserIterator(Api api) { this.api = api; }

    @Override
    public boolean hasNext() {
        if (buffer.isEmpty()) buffer = new ArrayDeque<>(api.getUsers(page++));
        return !buffer.isEmpty();
    }

    @Override
    public User next() {
        if (!hasNext()) throw new NoSuchElementException();
        return buffer.poll();
    }
}

Iterable<User> all = () -> new UserIterator(api);
for (User u : all) System.out.println(u.email());

Iterator in C#

iterator.cs 12 lines
async IAsyncEnumerable<User> Users(Api api)
{
    for (var page = 1; ; page++)
    {
        var batch = await api.GetUsersAsync(page);
        if (batch.Count == 0) yield break;
        foreach (var u in batch) yield return u;
    }
}

await foreach (var u in Users(api))
    Console.WriteLine(u.Email);

Iterator in PHP

iterator.php 16 lines
function users(Api $api): Generator
{
    for ($page = 1; ; $page++) {
        $batch = $api->get('/users', ['page' => $page]);
        if ($batch === []) {
            return;
        }
        yield from $batch;
    }
}

foreach (users($api) as $user) {
    echo $user['email'], PHP_EOL;
}

// Laravel: User::lazy() and User::cursor() apply the same principle

Iterator in Go

iterator.go 20 lines
// Go 1.23+: native iterators with iter.Seq
func Users(api *Api) iter.Seq[User] {
    return func(yield func(User) bool) {
        for page := 1; ; page++ {
            batch := api.GetUsers(page)
            if len(batch) == 0 {
                return
            }
            for _, u := range batch {
                if !yield(u) {
                    return // the client did a "break"
                }
            }
        }
    }
}

for u := range Users(api) {
    fmt.Println(u.Email)
}

Frequently asked questions

What is the Iterator design pattern?

Traverse the elements of a collection without exposing its internal representation (list, tree, paginated API…). Encapsulate the traversal in an iterator (next() / hasNext() or a generator). The client writes a plain for loop; the iterator loads pages on demand.

When should you use the Iterator pattern?

Complex collections (trees, graphs); Pagination, streaming, database cursors; Lazy traversal of large data sets.

What are the pros and cons of the Iterator pattern?

Pros: The client knows nothing about the internal structure; Several traversals can run at the same time; Lazy evaluation → memory under control. Cons: Overkill for a plain list; Handling network errors in the middle of an iteration.