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?
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:
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.
If the underlying representation were exposed, client code could couple to it. Then:
Data abstraction makes code more resilient to a change in the representation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With