Iterator
Intent
Walk through a collection’s items one by one without exposing how the collection stores them.
Motivation
A music app keeps a playlist internally as a list, but the player screen should not depend on that choice — tomorrow the storage could become a stream or a paged cache. Giving the playlist its own traversal object lets the screen ask “first song, next song, done?” while the list stays private and free to change.
Structure
flowchart LR Client[Player Client] --> It[Playlist Iterator] It --> Songs[Playlist Collection] Songs --> S1[Song A] Songs --> S2[Song B] Songs --> S3[Song C]
- Collection (Playlist) — owns the items and creates iterators; never hands out the raw list.
- Iterator — tracks position and answers first/next/done.
- Client (Player) — consumes items through the iterator only.
Consequences
- Benefit: traversal logic lives in one place; the collection can change storage and support several simultaneous walks.
- Cost: a tiny extra object per traversal; trivial for in-memory lists but worth noting.
Basic Recap
Iterator provides sequential access to elements without exposing the underlying collection’s representation. It encapsulates traversal state and offers a common way to advance and detect completion. Collections can therefore support arrays, trees, streams, or remote pages behind a consistent consumption model. An iterator is not automatically a snapshot or a transaction; its consistency and resource lifetime must be stated separately.
Complex Scenario
An audit service streams security events from a database cursor to an export worker. The iterator requests pages as needed and exposes each event in a stable format, so the exporter neither loads the full table nor constructs SQL. A cursor token records the last event key, and the iterator owns the cursor’s closure. Consumers can process days of history with bounded memory while the storage engine continues to optimize page access.
Edge cases
- Ordering: New inserts and updates during traversal can duplicate or skip events unless the query uses a keyset cursor and a defined high-water mark or snapshot.
- Partial failure: A failed page request should preserve the last committed cursor; after bounded retries, the iterator must close resources and surface the failure rather than silently ending the export.
- Memory pressure: Fetching the next page must be bounded and backpressured, because prefetching aggressively can recreate the full-table memory problem.
Completion should mean the defined range is exhausted, not that one transient page request happened to fail.
Sketch (illustrative pseudocode, not runnable):
AuditIterator.next():
if buffer.empty:
if finished:
return End
page = fetchPageAfter(cursor, highWaterMark, pageLimit)
buffer = page.events
cursor = page.nextCursor
finished = page.exhausted
return buffer.removeFirst()
Export.run(iterator):
try:
while iterator.hasNext:
event = iterator.next()
sink.append(event)
finally:
iterator.close()
When to Use / When Not to Use
Use when:
- Callers must visit every item but must not depend on storage details or index math.
- You need multiple traversal styles (forward, shuffle, filtered) over one collection.
Avoid when:
- The collection is a plain list nobody hides, and callers already iterate it directly with no pain.
Examples
examples/elixir/iterator/examples/dart/iterator/examples/go/iterator/examples/rust/iterator/
Expected outcome: the three playlist songs print in order without the client touching the raw list.
Anti-pattern / Failure Mode
-
Misuse: An iterator that exposes the storage it was meant to hide.
-
Review signal: Callers depending on iteration order that was never promised.
-
Misuse symptom: Iterator becomes an excuse to expose mutable internals or to hide unbounded network work behind a seemingly cheap
nextcall. Methods such ashasNextthat advance the cursor create duplicates and make ordinary loops unreliable. -
Review signal: Look for offset pagination over changing data, page failures mapped to end-of-stream, iterators without close operations, and traversal state shared between consumers. Export metrics should include pages fetched, retry counts, and the final cursor so a truncated file cannot be mistaken for a successful complete traversal.
Related
- Composite — walk trees uniformly.
- Observer — pull iteration vs push broadcasts.
- Information Hiding — the principle behind the curtain.
Exercise
Add a shuffle iterator that visits the same three songs in a different fixed order. The player code must work unchanged with either iterator.
Self-check
- What stays hidden from the client?
Answer
The storage shape and indexing — the client only sees first/next/done, never the underlying list. - How do two simultaneous walks coexist?
Answer
Each walk gets its own iterator object with its own position, both reading the same collection. - Why not just expose the list?
Answer
Exposing it locks the storage choice and lets callers mutate or index it; the iterator keeps one traversal contract while storage evolves.