At long last, we come to my number one pattern.  The iterator is one of those software concepts that you come across and do not know how you managed before you learned it.  Maybe it is just my frequent need to work through a collection of objects, but I think this is one of the most fundamental behavioral patterns you can master.

The Iterator Pattern Defined

As always, we will start with the “Gang of Four” intent to set the stage for our discussion.

“Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.”

Yes, this is the “while” syntax of software patterns.  The goal is to walk through a collection without regard to the underlying data or mechanism.  Thus, whether you have an array, a list, a linked list, a doubly linked list, or some other device for your collection, an iterator will give you sequential access.

Applying The Pattern

While a highly useful pattern, this also is one of the easiest to implement.  An iterator only requires a method for progressing to the next item in the collection.  It is helpful to include convenience functions like first, last, and a way to determine if you are at the beginning or end of a group.  However, those are not required to meet the stated intent.  While an iterator is roughly an interface, it does make sense to have concrete implementations of that interface that can be passed around.  That also gives the most flexibility.  A class can have a helper iterator class that progresses through properties and collections as needed for the utilization of the primary class.

Java, PHP, C#, etc.

There is nothing special required for an iterator (you do not even need inheritance).  However, most modern languages have built-in iterators for their core objects.  Thus, you might want to browse through the API before you try to build one on your own.  Likewise, there are numerous examples of how to use an iterator.  Therefore, if you are not comfortable with one then start there.

Rob Broadhead

Rob is a founder of, and frequent contributor to, Develpreneur. This includes the Building Better Developers podcast. He is also a lifetime learner as a developer, designer, and manager of software solutions. Rob is the founder of RB Consulting and has managed to author a book about his family experiences and a few about becoming a better developer. In his free time, he stays busy raising five children (although they have grown into adults). When he has a chance to breathe, he is on the ice playing hockey to relax or working on his ballroom dance skills.

Leave a Reply