Implementing Internal vs External Iterators
You'll learn the two fundamental approaches to iteration and when to use each one.
What Are Internal and External Iterators?
When implementing the Iterator pattern, you have two choices for who controls the traversal loop:
External iterators give the client explicit control. The client asks for the next element when they're ready, deciding when to advance and when to stop. Think of this like manually flipping through pages in a book—you control the pace and can pause anytime.
Internal iterators use callbacks. The collection controls the loop internally and calls your provided function for each element. It's like a guided tour—you tell the guide what you want to see, but they control the route and pace.
External Iterators
With external iterators, clients explicitly call methods like next(), hasNext(), or current(). You've seen this pattern: the client owns the loop and decides when to continue.
Benefits: Maximum flexibility—you can pause, compare two iterators side-by-side, or skip elements conditionally.
Trade-offs: More verbose code, clients must manage iterator state.
Internal Iterators
Internal iterators accept a callback function that executes for each element. The collection handles all traversal logic internally.
Benefits: Simpler client code, less room for traversal errors, easier to parallelize internally.
Trade-offs: Less control—you can't easily pause mid-iteration or process two collections in lockstep. Breaking out early requires special mechanisms (like exceptions or return values).
When to Choose Which
Use external when clients need fine-grained control over traversal or must coordinate multiple iterations simultaneously.
Use internal when the traversal pattern is straightforward and you want simpler, cleaner client code.
Key Takeaway: External iterators maximize client control at the cost of verbosity; internal iterators simplify client code but sacrifice flexibility in traversal control.