# Iterator: Next Stop, Please

When every piece of code that walks a route has its own loop over how the route is stored, changing the storage breaks all of them; an iterator hands out the stops one at a time, so callers ask for the next stop and never learn whether it came from a list, zones or a server.

Journeyman · OOP · Updated November 17, 2026

By Gregor Dzierzon

## After this lesson you can

- Give a collection an iterator, so callers can walk it without knowing how it's stored
- Spot the smells that point to Iterator: callers whose loops know how a collection is stored inside

## Key takeaways

- The smell: loops in many callers that reach into how a collection is stored, such as a loop over zones and then over each zone's stops.
- The cause: the knowledge of how the stops are stored has leaked into every caller, so a change to the storage is a change to all of them.
- The fix: the collection hands out an iterator, an object that answers two questions: is there another one, and what is it?
- Every for-each loop you've written used an iterator. Plugging yours into your language's iterator shape makes for-each work on your own collections.

**Before this:** *Meet the Package Tracker*, where Dana's route is a list of four streets, and interfaces (a promise any class can keep).

In version 1, Dana's route was a plain list: Maple St, Oak Ave, Pine Rd, Cedar Ln. Then the route team split routes into **zones**, so a dispatcher can hand the whole south side to another driver on a busy day. A sensible change to the route. Except that the driver's app, the printed manifest and the customer's "how many stops before mine?" screen all loop over the route themselves. By the end of this lesson you'll have met the *Iterator* pattern; first, what the zones did to those loops.

## The symptom: every caller knows about zones

Here is Dana's route with zones, and two of the places that walk it. North has Maple St and Oak Ave; South has Pine Rd and Cedar Ln:

```csharp
Route route = new Route("Dana", new List<Zone>
{
    new Zone("North", new List<string> { "Maple St", "Oak Ave" }),
    new Zone("South", new List<string> { "Pine Rd", "Cedar Ln" })
});
ShowStops(route);
PrintManifest(route);

// The driver's app.
void ShowStops(Route route)
{
    int number = 1;
    foreach (Zone zone in route.Zones)
    {
        foreach (string stop in zone.Stops)
        {
            Console.WriteLine($"Stop {number}: {stop}");
            number++;
        }
    }
}

// The printed manifest.
void PrintManifest(Route route)
{
    int count = 0;
    foreach (Zone zone in route.Zones)
    {
        count += zone.Stops.Count;
    }
    Console.WriteLine($"{route.Driver} has {count} stops");
}

record Zone(string Name, List<string> Stops);

class Route
{
    public string Driver { get; }
    public List<Zone> Zones { get; }
    public Route(string driver, List<Zone> zones) { Driver = driver; Zones = zones; }
}
```

```text
Stop 1: Maple St
Stop 2: Oak Ave
Stop 3: Pine Rd
Stop 4: Cedar Ln
Dana has 4 stops
```

```java
record Zone(String name, List<String> stops) {}

class Route {
    String driver;
    List<Zone> zones;
    Route(String driver, List<Zone> zones) { this.driver = driver; this.zones = zones; }
}

// The driver's app.
void showStops(Route route) {
    int number = 1;
    for (Zone zone : route.zones) {
        for (String stop : zone.stops()) {
            IO.println("Stop " + number + ": " + stop);
            number++;
        }
    }
}

// The printed manifest.
void printManifest(Route route) {
    int count = 0;
    for (Zone zone : route.zones) {
        count += zone.stops().size();
    }
    IO.println(route.driver + " has " + count + " stops");
}

void main() {
    Route route = new Route("Dana", List.of(
        new Zone("North", List.of("Maple St", "Oak Ave")),
        new Zone("South", List.of("Pine Rd", "Cedar Ln"))));
    showStops(route);
    printManifest(route);
}
```

```text
Stop 1: Maple St
Stop 2: Oak Ave
Stop 3: Pine Rd
Stop 4: Cedar Ln
Dana has 4 stops
```

```python
class Zone:
    def __init__(self, name, stops):
        self.name = name
        self.stops = stops


class Route:
    def __init__(self, driver, zones):
        self.driver = driver
        self.zones = zones


def show_stops(route):
    """The driver's app."""
    number = 1
    for zone in route.zones:
        for stop in zone.stops:
            print(f"Stop {number}: {stop}")
            number += 1


def print_manifest(route):
    """The printed manifest."""
    count = 0
    for zone in route.zones:
        count += len(zone.stops)
    print(f"{route.driver} has {count} stops")


route = Route("Dana", [Zone("North", ["Maple St", "Oak Ave"]), Zone("South", ["Pine Rd", "Cedar Ln"])])
show_stops(route)
print_manifest(route)
```

```text
Stop 1: Maple St
Stop 2: Oak Ave
Stop 3: Pine Rd
Stop 4: Cedar Ln
Dana has 4 stops
```

```javascript
class Zone {
  constructor(name, stops) {
    this.name = name;
    this.stops = stops;
  }
}

class Route {
  constructor(driver, zones) {
    this.driver = driver;
    this.zones = zones;
  }
}

// The driver's app.
function showStops(route) {
  let number = 1;
  for (const zone of route.zones) {
    for (const stop of zone.stops) {
      console.log(`Stop ${number}: ${stop}`);
      number++;
    }
  }
}

// The printed manifest.
function printManifest(route) {
  let count = 0;
  for (const zone of route.zones) {
    count += zone.stops.length;
  }
  console.log(`${route.driver} has ${count} stops`);
}

const route = new Route("Dana", [new Zone("North", ["Maple St", "Oak Ave"]), new Zone("South", ["Pine Rd", "Cedar Ln"])]);
showStops(route);
printManifest(route);
```

```text
Stop 1: Maple St
Stop 2: Oak Ave
Stop 3: Pine Rd
Stop 4: Cedar Ln
Dana has 4 stops
```

```typescript
class Zone {
  name: string;
  stops: string[];

  constructor(name: string, stops: string[]) {
    this.name = name;
    this.stops = stops;
  }
}

class Route {
  driver: string;
  zones: Zone[];

  constructor(driver: string, zones: Zone[]) {
    this.driver = driver;
    this.zones = zones;
  }
}

// The driver's app.
function showStops(route: Route): void {
  let number = 1;
  for (const zone of route.zones) {
    for (const stop of zone.stops) {
      console.log(`Stop ${number}: ${stop}`);
      number++;
    }
  }
}

// The printed manifest.
function printManifest(route: Route): void {
  let count = 0;
  for (const zone of route.zones) {
    count += zone.stops.length;
  }
  console.log(`${route.driver} has ${count} stops`);
}

const route = new Route("Dana", [new Zone("North", ["Maple St", "Oak Ave"]), new Zone("South", ["Pine Rd", "Cedar Ln"])]);
showStops(route);
printManifest(route);
```

```text
Stop 1: Maple St
Stop 2: Oak Ave
Stop 3: Pine Rd
Stop 4: Cedar Ln
Dana has 4 stops
```

It works. It also took an afternoon: when the route went from a list to zones, every loop over `route.Stops` stopped compiling, and each one was rewritten into a loop inside a loop. Next year the stops will come from the company's route server, a page at a time, and every one of those loops will be rewritten again.

- **The symptom:** the same nested loop, over zones and then over each zone's stops, in every piece of code that walks the route.
- **The cause:** how the route *stores* its stops has leaked into everyone who *reads* them. The driver's app only wants "the next stop"; it shouldn't need to know that zones exist.

## What would you try?

**Hand out the zones and let each caller loop.** That's the code above. Every caller pays for every storage change.

**Copy the stops into a plain list whenever someone asks.** `route.AllStops()` builds a fresh list each time. It works, and it's often fine for four stops. But it builds the whole list even when the driver only needs the next stop, and it can't work when the stops arrive from a server a page at a time.

**Give the route an index method, `StopAt(n)`.** Each call has to count its way through the zones to the nth stop, every time, and "stop number n" stops meaning anything when stops come in pages.

What we want is for the route to keep a bookmark: "you've had Maple St and Oak Ave; Pine Rd is next". The caller asks for the next stop, and only the route knows how to find it.

## The everyday version: the channel-up button

A TV remote's channel-up button works this way. You press it and you get the next channel. You don't know, or care, whether the channels come from an antenna, a cable box or a streaming app, or how they're numbered inside. The button keeps your place and hands you the next one.

![A TV remote held in a hand, a thumb on its channel-up button, while the TV across the room changes from channel 4 to channel 5](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/4b5a09531ec74f4d8a592cfbbc6c5336.webp)

## The fix: hand out an iterator

The route hands out a small object, an **iterator**, that keeps the bookmark and answers two questions: *is there another stop?* and *what is it?* The callers ask the iterator; only the iterator knows about zones:

![Iterator's roles: the driver's app and the manifest each ask the route's iterator "is there a next stop? what is it?", and the iterator reads the route, keeping its place. The iterator and the route share a dashed fence labeled "what changes: how the stops are stored"](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/f51e76c95de3464aa5f85be4cb851f87.webp)

The fence holds the route and its iterator together, because they change together. When storage changes, those two change; the callers outside the fence don't.

## How it got its name

An object that walks through a collection one item at a time, keeping its place, without showing how the collection is stored, is an **iterator**, and handing one out is the **Iterator pattern**. It's in the original 1994 book, and it's now built into every language you'll use.

## The classic version

The book's iterator has two methods, `hasNext` and `next`. The route makes one with `CreateIterator`, and each caller loops until there are no more stops:

```csharp
Route route = new Route("Dana", new List<Zone>
{
    new Zone("North", new List<string> { "Maple St", "Oak Ave" }),
    new Zone("South", new List<string> { "Pine Rd", "Cedar Ln" })
});
ShowStops(route);
PrintManifest(route);

// The callers ask for the next stop; neither knows about zones.
void ShowStops(Route route)
{
    RouteIterator stops = route.CreateIterator();
    int number = 1;
    while (stops.HasNext())
    {
        Console.WriteLine($"Stop {number}: {stops.Next()}");
        number++;
    }
}

void PrintManifest(Route route)
{
    RouteIterator stops = route.CreateIterator();
    int count = 0;
    while (stops.HasNext())
    {
        stops.Next();
        count++;
    }
    Console.WriteLine($"{route.Driver} has {count} stops");
}

record Zone(string Name, List<string> Stops);

class Route
{
    private readonly List<Zone> zones;
    public string Driver { get; }
    public Route(string driver, List<Zone> zones) { Driver = driver; this.zones = zones; }
    public RouteIterator CreateIterator() => new RouteIterator(zones);
}

// Keeps a bookmark: which zone, and which stop in it.
class RouteIterator
{
    private readonly List<Zone> zones;
    private int zone = 0;
    private int stop = 0;
    public RouteIterator(List<Zone> zones) { this.zones = zones; }

    public bool HasNext()
    {
        while (zone < zones.Count && stop >= zones[zone].Stops.Count)
        {
            zone++;
            stop = 0;
        }
        return zone < zones.Count;
    }

    public string Next()
    {
        if (!HasNext()) { throw new InvalidOperationException("No more stops"); }
        string next = zones[zone].Stops[stop];
        stop++;
        return next;
    }
}
```

```text
Stop 1: Maple St
Stop 2: Oak Ave
Stop 3: Pine Rd
Stop 4: Cedar Ln
Dana has 4 stops
```

```java
record Zone(String name, List<String> stops) {}

// Keeps a bookmark: which zone, and which stop in it.
class RouteIterator {
    List<Zone> zones;
    int zone = 0;
    int stop = 0;
    RouteIterator(List<Zone> zones) { this.zones = zones; }

    boolean hasNext() {
        while (zone < zones.size() && stop >= zones.get(zone).stops().size()) {
            zone++;
            stop = 0;
        }
        return zone < zones.size();
    }

    String next() {
        if (!hasNext()) { throw new NoSuchElementException("No more stops"); }
        String next = zones.get(zone).stops().get(stop);
        stop++;
        return next;
    }
}

class Route {
    String driver;
    List<Zone> zones;
    Route(String driver, List<Zone> zones) { this.driver = driver; this.zones = zones; }
    RouteIterator createIterator() { return new RouteIterator(zones); }
}

// The callers ask for the next stop; neither knows about zones.
void showStops(Route route) {
    RouteIterator stops = route.createIterator();
    int number = 1;
    while (stops.hasNext()) {
        IO.println("Stop " + number + ": " + stops.next());
        number++;
    }
}

void printManifest(Route route) {
    RouteIterator stops = route.createIterator();
    int count = 0;
    while (stops.hasNext()) {
        stops.next();
        count++;
    }
    IO.println(route.driver + " has " + count + " stops");
}

void main() {
    Route route = new Route("Dana", List.of(
        new Zone("North", List.of("Maple St", "Oak Ave")),
        new Zone("South", List.of("Pine Rd", "Cedar Ln"))));
    showStops(route);
    printManifest(route);
}
```

```text
Stop 1: Maple St
Stop 2: Oak Ave
Stop 3: Pine Rd
Stop 4: Cedar Ln
Dana has 4 stops
```

```python
class Zone:
    def __init__(self, name, stops):
        self.name = name
        self.stops = stops


class RouteIterator:
    """Keeps a bookmark: which zone, and which stop in it."""

    def __init__(self, zones):
        self.zones = zones
        self.zone = 0
        self.stop = 0

    def has_next(self):
        while self.zone < len(self.zones) and self.stop >= len(self.zones[self.zone].stops):
            self.zone += 1
            self.stop = 0
        return self.zone < len(self.zones)

    def next(self):
        if not self.has_next():
            raise IndexError("No more stops")
        stop = self.zones[self.zone].stops[self.stop]
        self.stop += 1
        return stop


class Route:
    def __init__(self, driver, zones):
        self.driver = driver
        self._zones = zones

    def create_iterator(self):
        return RouteIterator(self._zones)


# The callers ask for the next stop; neither knows about zones.
def show_stops(route):
    stops = route.create_iterator()
    number = 1
    while stops.has_next():
        print(f"Stop {number}: {stops.next()}")
        number += 1


def print_manifest(route):
    stops = route.create_iterator()
    count = 0
    while stops.has_next():
        stops.next()
        count += 1
    print(f"{route.driver} has {count} stops")


route = Route("Dana", [Zone("North", ["Maple St", "Oak Ave"]), Zone("South", ["Pine Rd", "Cedar Ln"])])
show_stops(route)
print_manifest(route)
```

```text
Stop 1: Maple St
Stop 2: Oak Ave
Stop 3: Pine Rd
Stop 4: Cedar Ln
Dana has 4 stops
```

```javascript
class Zone {
  constructor(name, stops) {
    this.name = name;
    this.stops = stops;
  }
}

// Keeps a bookmark: which zone, and which stop in it.
class RouteIterator {
  zone = 0;
  stop = 0;

  constructor(zones) {
    this.zones = zones;
  }

  hasNext() {
    while (this.zone < this.zones.length && this.stop >= this.zones[this.zone].stops.length) {
      this.zone++;
      this.stop = 0;
    }
    return this.zone < this.zones.length;
  }

  next() {
    if (!this.hasNext()) { throw new Error("No more stops"); }
    const next = this.zones[this.zone].stops[this.stop];
    this.stop++;
    return next;
  }
}

class Route {
  #zones;

  constructor(driver, zones) {
    this.driver = driver;
    this.#zones = zones;
  }

  createIterator() {
    return new RouteIterator(this.#zones);
  }
}

// The callers ask for the next stop; neither knows about zones.
function showStops(route) {
  const stops = route.createIterator();
  let number = 1;
  while (stops.hasNext()) {
    console.log(`Stop ${number}: ${stops.next()}`);
    number++;
  }
}

function printManifest(route) {
  const stops = route.createIterator();
  let count = 0;
  while (stops.hasNext()) {
    stops.next();
    count++;
  }
  console.log(`${route.driver} has ${count} stops`);
}

const route = new Route("Dana", [new Zone("North", ["Maple St", "Oak Ave"]), new Zone("South", ["Pine Rd", "Cedar Ln"])]);
showStops(route);
printManifest(route);
```

```text
Stop 1: Maple St
Stop 2: Oak Ave
Stop 3: Pine Rd
Stop 4: Cedar Ln
Dana has 4 stops
```

```typescript
class Zone {
  name: string;
  stops: string[];

  constructor(name: string, stops: string[]) {
    this.name = name;
    this.stops = stops;
  }
}

// Keeps a bookmark: which zone, and which stop in it.
class RouteIterator {
  zones: Zone[];
  zone = 0;
  stop = 0;

  constructor(zones: Zone[]) {
    this.zones = zones;
  }

  hasNext(): boolean {
    while (this.zone < this.zones.length && this.stop >= this.zones[this.zone].stops.length) {
      this.zone++;
      this.stop = 0;
    }
    return this.zone < this.zones.length;
  }

  next(): string {
    if (!this.hasNext()) { throw new Error("No more stops"); }
    const next = this.zones[this.zone].stops[this.stop];
    this.stop++;
    return next;
  }
}

class Route {
  driver: string;
  private zones: Zone[];

  constructor(driver: string, zones: Zone[]) {
    this.driver = driver;
    this.zones = zones;
  }

  createIterator(): RouteIterator {
    return new RouteIterator(this.zones);
  }
}

// The callers ask for the next stop; neither knows about zones.
function showStops(route: Route): void {
  const stops = route.createIterator();
  let number = 1;
  while (stops.hasNext()) {
    console.log(`Stop ${number}: ${stops.next()}`);
    number++;
  }
}

function printManifest(route: Route): void {
  const stops = route.createIterator();
  let count = 0;
  while (stops.hasNext()) {
    stops.next();
    count++;
  }
  console.log(`${route.driver} has ${count} stops`);
}

const route = new Route("Dana", [new Zone("North", ["Maple St", "Oak Ave"]), new Zone("South", ["Pine Rd", "Cedar Ln"])]);
showStops(route);
printManifest(route);
```

```text
Stop 1: Maple St
Stop 2: Oak Ave
Stop 3: Pine Rd
Stop 4: Cedar Ln
Dana has 4 stops
```

Same five lines, and neither `ShowStops` nor `PrintManifest` mentions a zone. The route keeps its zones to itself now, so nobody outside can loop over them by accident. When the stops move to the route server, `RouteIterator` changes and the callers don't. Here is one walk of the route as a sequence diagram:

![A sequence diagram of walking the route: the driver's app asks Route for an iterator, which Route creates. Then, in a loop frame "while hasNext()", the app asks the iterator hasNext() (true) and next() ("Maple St"), one stop at a time](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/3f997d38d46b45c8a7b228e9c4d7e2df.webp)

## The modern version: your language's own iterator

Every language here already has an iterator built in, and it's what your for-each loop calls behind the scenes. Give your iterator the shape your language expects, and for-each works on a `Route` too:

```csharp
Route route = new Route("Dana", new List<Zone>
{
    new Zone("North", new List<string> { "Maple St", "Oak Ave" }),
    new Zone("South", new List<string> { "Pine Rd", "Cedar Ln" })
});
ShowStops(route);
PrintManifest(route);

// foreach works on a Route now, because it hands out an IEnumerator.
void ShowStops(Route route)
{
    int number = 1;
    foreach (string stop in route)
    {
        Console.WriteLine($"Stop {number}: {stop}");
        number++;
    }
}

void PrintManifest(Route route) => Console.WriteLine($"{route.Driver} has {route.Count()} stops");

record Zone(string Name, List<string> Stops);

class Route : IEnumerable<string>
{
    private readonly List<Zone> zones;
    public string Driver { get; }
    public Route(string driver, List<Zone> zones) { Driver = driver; this.zones = zones; }
    public IEnumerator<string> GetEnumerator() => new RouteIterator(zones);
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}

class RouteIterator : IEnumerator<string>
{
    private readonly List<Zone> zones;
    private int zone = 0;
    private int stop = -1;
    public RouteIterator(List<Zone> zones) { this.zones = zones; }

    public string Current => zones[zone].Stops[stop];
    object System.Collections.IEnumerator.Current => Current;

    public bool MoveNext()
    {
        stop++;
        while (zone < zones.Count && stop >= zones[zone].Stops.Count)
        {
            zone++;
            stop = 0;
        }
        return zone < zones.Count;
    }

    public void Reset() { zone = 0; stop = -1; }
    public void Dispose() { }
}
```

```text
Stop 1: Maple St
Stop 2: Oak Ave
Stop 3: Pine Rd
Stop 4: Cedar Ln
Dana has 4 stops
```

```java
record Zone(String name, List<String> stops) {}

class RouteIterator implements Iterator<String> {
    List<Zone> zones;
    int zone = 0;
    int stop = 0;
    RouteIterator(List<Zone> zones) { this.zones = zones; }

    public boolean hasNext() {
        while (zone < zones.size() && stop >= zones.get(zone).stops().size()) {
            zone++;
            stop = 0;
        }
        return zone < zones.size();
    }

    public String next() {
        if (!hasNext()) { throw new NoSuchElementException("No more stops"); }
        String next = zones.get(zone).stops().get(stop);
        stop++;
        return next;
    }
}

// for-each works on a Route now, because it's Iterable.
class Route implements Iterable<String> {
    String driver;
    private List<Zone> zones;
    Route(String driver, List<Zone> zones) { this.driver = driver; this.zones = zones; }
    public Iterator<String> iterator() { return new RouteIterator(zones); }
}

void showStops(Route route) {
    int number = 1;
    for (String stop : route) {
        IO.println("Stop " + number + ": " + stop);
        number++;
    }
}

void printManifest(Route route) {
    int count = 0;
    for (String stop : route) { count++; }
    IO.println(route.driver + " has " + count + " stops");
}

void main() {
    Route route = new Route("Dana", List.of(
        new Zone("North", List.of("Maple St", "Oak Ave")),
        new Zone("South", List.of("Pine Rd", "Cedar Ln"))));
    showStops(route);
    printManifest(route);
}
```

```text
Stop 1: Maple St
Stop 2: Oak Ave
Stop 3: Pine Rd
Stop 4: Cedar Ln
Dana has 4 stops
```

```python
class Zone:
    def __init__(self, name, stops):
        self.name = name
        self.stops = stops


class RouteIterator:
    def __init__(self, zones):
        self.zones = zones
        self.zone = 0
        self.stop = 0

    def __iter__(self):
        return self

    def __next__(self):
        while self.zone < len(self.zones) and self.stop >= len(self.zones[self.zone].stops):
            self.zone += 1
            self.stop = 0
        if self.zone >= len(self.zones):
            raise StopIteration
        stop = self.zones[self.zone].stops[self.stop]
        self.stop += 1
        return stop


class Route:
    """for works on a Route now, because it hands out an iterator."""

    def __init__(self, driver, zones):
        self.driver = driver
        self._zones = zones

    def __iter__(self):
        return RouteIterator(self._zones)


def show_stops(route):
    for number, stop in enumerate(route, start=1):
        print(f"Stop {number}: {stop}")


def print_manifest(route):
    print(f"{route.driver} has {sum(1 for stop in route)} stops")


route = Route("Dana", [Zone("North", ["Maple St", "Oak Ave"]), Zone("South", ["Pine Rd", "Cedar Ln"])])
show_stops(route)
print_manifest(route)
```

```text
Stop 1: Maple St
Stop 2: Oak Ave
Stop 3: Pine Rd
Stop 4: Cedar Ln
Dana has 4 stops
```

```javascript
class Zone {
  constructor(name, stops) {
    this.name = name;
    this.stops = stops;
  }
}

class RouteIterator {
  zone = 0;
  stop = 0;

  constructor(zones) {
    this.zones = zones;
  }

  next() {
    while (this.zone < this.zones.length && this.stop >= this.zones[this.zone].stops.length) {
      this.zone++;
      this.stop = 0;
    }
    if (this.zone >= this.zones.length) { return { done: true, value: undefined }; }
    const value = this.zones[this.zone].stops[this.stop];
    this.stop++;
    return { done: false, value };
  }
}

// for...of works on a Route now, because it hands out an iterator.
class Route {
  #zones;

  constructor(driver, zones) {
    this.driver = driver;
    this.#zones = zones;
  }

  [Symbol.iterator]() {
    return new RouteIterator(this.#zones);
  }
}

function showStops(route) {
  let number = 1;
  for (const stop of route) {
    console.log(`Stop ${number}: ${stop}`);
    number++;
  }
}

function printManifest(route) {
  console.log(`${route.driver} has ${[...route].length} stops`);
}

const route = new Route("Dana", [new Zone("North", ["Maple St", "Oak Ave"]), new Zone("South", ["Pine Rd", "Cedar Ln"])]);
showStops(route);
printManifest(route);
```

```text
Stop 1: Maple St
Stop 2: Oak Ave
Stop 3: Pine Rd
Stop 4: Cedar Ln
Dana has 4 stops
```

```typescript
class Zone {
  name: string;
  stops: string[];

  constructor(name: string, stops: string[]) {
    this.name = name;
    this.stops = stops;
  }
}

class RouteIterator implements Iterator<string> {
  zones: Zone[];
  zone = 0;
  stop = 0;

  constructor(zones: Zone[]) {
    this.zones = zones;
  }

  next(): IteratorResult<string> {
    while (this.zone < this.zones.length && this.stop >= this.zones[this.zone].stops.length) {
      this.zone++;
      this.stop = 0;
    }
    if (this.zone >= this.zones.length) { return { done: true, value: undefined }; }
    const value = this.zones[this.zone].stops[this.stop];
    this.stop++;
    return { done: false, value };
  }
}

// for...of works on a Route now, because it hands out an iterator.
class Route implements Iterable<string> {
  driver: string;
  private zones: Zone[];

  constructor(driver: string, zones: Zone[]) {
    this.driver = driver;
    this.zones = zones;
  }

  [Symbol.iterator](): Iterator<string> {
    return new RouteIterator(this.zones);
  }
}

function showStops(route: Route): void {
  let number = 1;
  for (const stop of route) {
    console.log(`Stop ${number}: ${stop}`);
    number++;
  }
}

function printManifest(route: Route): void {
  console.log(`${route.driver} has ${[...route].length} stops`);
}

const route = new Route("Dana", [new Zone("North", ["Maple St", "Oak Ave"]), new Zone("South", ["Pine Rd", "Cedar Ln"])]);
showStops(route);
printManifest(route);
```

```text
Stop 1: Maple St
Stop 2: Oak Ave
Stop 3: Pine Rd
Stop 4: Cedar Ln
Dana has 4 stops
```

The callers are back to plain for-each loops, and everything your language does with a collection now works on a route: C#'s `Count()`, Python's `enumerate` and `sum`, JavaScript's spread `[...route]`.

**Where the languages differ.** Each language names the two questions its own way. C# asks `MoveNext()` (move, and say whether there was one) and then reads `Current`. Java's `Iterator` *is* the book's `hasNext` and `next`. Python calls `__next__` and expects `StopIteration` at the end. JavaScript and TypeScript call `next()` and get back `{ done, value }`. That's a lot of bookkeeping for "next stop, please", and the next lesson shows how most of it disappears.

## Where you've already used it

- **Every for-each loop:** `foreach` in C#, `for (x : list)` in Java, `for x in` in Python, `for…of` in JavaScript. Each one asks the collection for an iterator and calls it until there's nothing left.
- **Reading a file line by line** in Python (`for line in open("routes.txt")`): the file hands out one line at a time and never loads the whole file.
- **Rows from a database query**, read one at a time by a data reader or cursor.

## When not to use it

- **When the collection is a plain list and will stay one.** A list already has an iterator; writing your own class adds nothing.
- **When callers really need the structure.** A dispatcher's screen that shows zones *as zones* should get the zones. An iterator hides structure; don't hide what the caller needs to see.

The cost of a hand-written iterator is the bookkeeping you saw: a bookmark, edge cases for empty zones, and each language's own method names. The next lesson removes most of it.

**How often you'll meet it:** every day as a user, in every for-each loop; writing your own, now and then (our estimate).

## Check yourself

2 questions to try on the lesson page.

## So what

When every caller's loop knows how a collection is stored, hand out an iterator instead. The storage can change from a list to zones to pages from a server, and the code that walks it never notices.

## Key terms

- [Iterator Pattern](https://www.ask-codey.com/glossary/iterator-pattern)
- [Encapsulation](https://www.ask-codey.com/glossary/encapsulation-oop)
- [Code Smell](https://www.ask-codey.com/glossary/code-smell)

## Cheat sheets

- [Iterator: Next Stop, Please](https://www.ask-codey.com/cheat-sheets/dp-iterator-cheat-sheet)

Source: https://www.ask-codey.com/lessons/dp-iterator
