Design Patterns Revisited: Iterator

The Iterator Pattern came under attack. I shall take on the task of defending the Gof(as it's turning out)! So, okay, yes, yes, the iterator pattern as implemented in the way the class diagram - there's no better way to say it. This is the way the Iterator is implemented in the standard Java library. People hip to dynamic languages like python and smalltalk will point out that the iterator pattern looks much sexier in those languages. Yes, yes. The criticism in the "Design Patterns aren't" slide is that people copy and paste the code samples over and over again into their own code base. There are a few holes in this criticism.

  1. the "do it over and over again" retoric is not entirely correct. The concrete implementations of the iterator has to be implemented over and over, but not the Iterator interface itself. In fact, in the Java standard library, there's only one universal Iterator interface.
  2. If the only stuff that has to be done over and over again is the iterator implementations, this is not any different in dynamic languages
  3. The Gof does mention very specifically the different kinds of iterator patterns, in particular:
    1. external iterator - where the client of the iterator controls the iteration(generally how it's done in Java, C++ and python)
    2. internal iteration - where the client passes the iterator a code block, or closure, and the iterator controls the iteration(smalltalk, ruby)
    3. Some languages have iterators built right into the language(python, ruby)
  4. Although the code samples were in C++ only, Gof did give examples for both external and internal iterators, although internal iterators in C++ still suck, so it wasn't a good example(they used a template method pattern to do it, which is not very generic)

So, basically, I find the criticism in these slides unfair. Of course, all I have to go on are the slides, I don't have a clue as to what was said by the presenter. To give him the benefit of the doubt, he could just be saying that people are mis-using the Gof book. But then again, in the next few slides he starts to show off how iterator is done in perl and lisp, so probably not.

What does this all mean? People, if you have the Gof book, read it! Really read it, before you really go attacking it. I mean to say something about Christopher Alexander, but will leave it for a later post.

Update: However, I do agree with the point that much of what the book covers is how to implement the patterns in C++, which is much cluggier than in many dynamic languages. But there's a reason for this: some people just don't have a choice to which the language they use. This was more so in the 90s when C/C++ was the fastest platform but is still the case today where Java dominates the enterprise.

blog comments powered by Disqus