Better Programming

Advice for programmers.

Follow publication

Member-only story

Understanding the Iterator Design Pattern Using the Dev.to and Medium Social Networks

Carlos Caballero
Better Programming
Published in
8 min readNov 25, 2019
Photo by NordWood Themes on Unsplash

There are 23 classic design patterns described in the original book, Design Patterns: Elements of Reusable Object-Oriented Software. These patterns provide solutions to particular problems, often repeated in software development.

In this article, I am going to describe what the Iterator Pattern is and how and when it should be applied.

Iterator Pattern: Basic Idea

In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container’s elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled. — Wikipedia

Provide a way to access the elements of an aggregate object sequentially
without exposing its underlying representation. — Design Patterns: Elements of Reusable Object-Oriented Software

The main feature of this pattern is that it lets you traverse elements of a collection without exposing its underlying representation (array, map, tree, etc.). Therefore, these are two problems that this pattern resolves:

  1. It allows us to change the internal implementation of a collection with no change in the algorithm’s implementation.
  2. It allows us to add new algorithms that work all existing collection types.

To sum up, the iterator pattern hides the internal implementation of a collection from the client. The UML diagram of this pattern is the following one:

The Iterator class is an interface which defines the different operations to navigate through to the collection ( next or hasNext) while that Aggregate class will create the Iterator. Finally, the system will use the ConcreteAggregate and ConcreteIterator.

  1. Your collection has a complex data structure under the hood, but you want to hide its complexity from clients.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Carlos Caballero
Carlos Caballero

Written by Carlos Caballero

Hi! My name is Carlos Caballero and I’m PhD. in Computer Science from Málaga, Spain. Teaching developers and degree/master computer science how to be experts!

No responses yet

Write a response