I’ve been discussing AntiPatterns quite a bit lately, so I elected to switch it up and talk a bit about Anti-AntiPatterns, aka Design Patterns. As a quick recap: If AntiPatterns are common bad practice traps that developers/teams can fall into, then Design Patterns are good practices which help guide them to either avoid AntiPatterns, or to lean towards a more efficient solution.
One design pattern we’ve used many times in my Data Structures class is the iterator, and personally feel as though it was never fully explained to the class as to what an iterator even really is, let alone why we were writing one. This post from Sourcemaking.com helped a lot in terms of learning what the use of them is.
As covered in the article, there has been a push in recent programming towards something called “Generic Programming”, and the iterator is a core idea within it. An iterator is an attempt to abstract out the traversal of data items in a data structure into a separate thing. The usefulness of this is outlined by an example given in the article:
“As an example, if you wanted to support four data structures (array, binary tree, linked list, and hash table) and three algorithms (sort, find, and merge), a traditional approach would require four times three permutations to develop and maintain. Whereas, a generic programming approach would only require four plus three configuration items.”
– Sourcemaking.com
So essentially, your iterator is an object in itself that handles the job of traversing through the objects in a list. A real-world example of this may be the AM/FM radio controls in your car. The radio stations are the objects in a list, with their station name and frequency (or channel, I suppose) as their data. The iterator would be your “scan” button, which skips over the stations with fuzzy signals in order to reach the next one whose frequency is available to you, while all you did was press the one button. Each station is a data point in your list (your data structure) with a station name and a frequency. You, the driver, don’t need to know anything about the details of the stations you’re scanning over, because the iterator (the scan button) handles that for you when finding the next available station.
The article from Sourcemaking has several really great UML diagrams and other examples to pick apart which help elaborate on the subject even further. I highly suggest visiting their website to read more about it — they have detailed explanations on almost every type of AntiPattern and Design Pattern I’ve looked into so far.
From the blog CS@Worcester – James Blash by jwblash and used with permission of the author. All other rights reserved by the author.