Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is exposing an iterators underlying representation bad?

Iterator Pattern Definition: Provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. Wiki

What are the consequences of exposing the underlying representation?

To provide a more detailed answer: How is the iterator pattern preventing this?

like image 309
Waddas Avatar asked May 20 '13 17:05

Waddas


3 Answers

As per: http://www.oodesign.com/iterator-pattern.html

The idea of the iterator pattern is to take the responsibility of accessing and passing trough the objects of the collection and put it in the iterator object. The iterator object will maintain the state of the iteration, keeping track of the current item and having a way of identifying what elements are next to be iterated.

Few benefits that you can get from this pattern:

  1. Using Iterator pattern code designer can decide whether to allow 1 way iteration (using next() only) or allow reverse iteration as well (using prev() as in ListIterator).
  2. Whether to allow object removal or not, if yes then how.
  3. Maintain internal housekeeping when object is removed.
  4. It allows you to expose common mechanism of traversing a collection rather than expecting your clients to understand underlying collections.
like image 132
anubhava Avatar answered Sep 30 '22 09:09

anubhava


In short: all the code relying on the underlying representation will have to be changed if you decide to change the representation.

E.g., you decided to use TreeMap at first, but then you don't want ordering anymore (in most cases), so you change to HashMap. Somebody is looping through your map trying to get a increasing list. !!

Using iterator pattern, you could always give the user the ability to loop through something with a certain logic (or just random, which is a kind of logic) without knowing what it is under the hood.

Now, if you use HashMap instead of TreeMap, you could expose a sorted view to the user. If you provide this SortedIterator and tell user "using this will guarantee the result to be sorted, but I can't tell you anything about what's underneath", you can change the representation to be whatever you like, as long as the contract of this SortedIterator is maintained by you.

like image 34
zw324 Avatar answered Sep 30 '22 08:09

zw324


If the underlying representation were exposed, client code could couple to it. Then:

  • If the representation changes, it may be necessary to change all the code coupling to it.
  • If you want to iterate over a different type of container, it may be necessary to change the code coupling to the old container.

Data abstraction makes code more resilient to a change in the representation.

like image 41
Andy Thomas Avatar answered Sep 30 '22 07:09

Andy Thomas