Card 09/ 09
Recap: Iterator Pattern
Walk one item at a time without seeing the storage, and an iterator, once used, is empty.
Iterator lets code walk any collection one element at a time without knowing how it is stored.
- Intent. Access the elements of an aggregate in sequence without exposing its representation.
- Structure. The aggregate creates iterators; each iterator keeps its own position, so walks do not interfere.
- In each language.
__iter__and__next__in Python,IterableandIteratorin Java,[Symbol.iterator]()andnext()in TypeScript. - On demand. An iterator can fetch or compute each element only when it is asked, such as the next page of results from a server.
- In Python. A generator is an iterator with the position kept for you, and the usual way to write one.
- The trap. An iterator used up is empty; return a fresh one from
__iter__, or turn it into a list once. - When not. A plain list that already has an iterator, or callers that need access by position.
← → move through sections and cards