Skip to content

Iterator Pattern: Sequential Access Without Exposure

Walk a collection without exposing its internals

Builds on Collections: which one to pick

Stage 3core2 min read

The Leaky Collection Problem

The YouTubePlaylist does not protect its own data. It hands the whole internal list to the client. The class then loses control of its state, and the client must work out how to walk through the list.


1. Understanding the Issue

In the code, YouTubePlaylist is a thin wrapper around a List<Video>. Its getVideos() method returns that internal list. This is a Leaky Abstraction: a detail that should be hidden leaks out. The client is no longer just using the playlist. It is handling the playlist's storage.


2. What are the Issues?

Exposes Internal Structure

  • The Issue: getVideos() returns the internal list itself.
  • The Impact: This breaks encapsulation (a class keeps its data private). A client can change the list from outside, for example with .clear() or .remove(). This skips any business rules or checks the class has.

Tight Coupling with Underlying Structure

  • The Issue: Outside code depends on the exact collection type (like ArrayList, Vector, or LinkedList).
  • The Impact: Say you switch to a Map for faster lookups or a PriorityQueue for sorting. Every piece of client code that calls getVideos() will break.

No Control Over Traversal

  • The Issue: The code that walks through the list lives outside the class.
  • The Impact: To add shuffle play, reverse order, or hiding private videos, you must edit every client. The walking logic is scattered everywhere.

Difficult to Support Multiple Independent Traversals

  • The Issue: No object tracks the "current position" of a scan.
  • The Impact: If two parts of your program read the same playlist at the same time, each must keep its own index by hand. This repeats code and invites mistakes.

3. Structural Analysis

ComponentStatusObservation
EncapsulationBrokenInternal List is public property via the getter.
Client CodeOver-burdenedClient must know how to loop through a List.
FlexibilityLowChanging the data structure requires a full refactor.

4. Summary of the "Smell"

When a class says "Here is my internal list, go loop through it yourself," it is giving up its job. A good collection lets you get its elements one by one without showing how they are stored. The Iterator Pattern does this. It gives you a standard "Remote Control" to move through the collection.

In this topic

Before code1 file

Before/Main.java64 linesGitHub
package DesignPatterns.BehaviouralPatterns.IteratorPattern.Before;import java.util.ArrayList;import java.util.List;// A simple Video class with titleclass Video {    String title;    public Video(String title) {        this.title = title;    }    public String getTitle() {        return title;    }}/** * PROBLEM: Encapsulation Breach. * The playlist exposes its internal data structure (ArrayList) to the outside * world. */class YouTubePlaylist {    // INTERNAL STATE: What if we want to change this to a Set or a LinkedHashMap    // later?    private List<Video> videos = new ArrayList<>();    public void addVideo(Video video) {        videos.add(video);    }    /**     * ISSUE 1: EXPOSING THE DATA STRUCTURE     * By returning 'List<Video>', you allow the client to know EXACTLY how     * data is stored. If you change 'List' to 'Map', every client using this method     * breaks.     * * ISSUE 2: LACK OF CONTROL     * The client can now call playlist.getVideos().clear() and empty your     * playlist without permission.     */    public List<Video> getVideos() {        return videos;    }}// Client Codeclass Main {    public static void main(String[] args) {        YouTubePlaylist playlist = new YouTubePlaylist();        playlist.addVideo(new Video("LLD Tutorial"));        playlist.addVideo(new Video("System Design Basics"));        /**         * ISSUE 3: TIGHT COUPLING         * The client is responsible for the "How" of traversal.         * If the playlist were a complex tree structure, the client         * would need to implement a complex Depth-First Search here.         */        for (Video v : playlist.getVideos()) {            System.out.println(v.getTitle());        }    }}

Done with this topic?

How well do you know it?

PreviousInverted Control & Structural Governance