intermediateIterator Pattern

Why does exposing a collection's raw backing structure to client code create a real maintenance risk?

The moment client code calls a method like get(i) or relies on any other structure-specific operation, that code becomes tightly coupled to exactly one implementation detail — that the collection happens to be backed by something indexable, like a List. If the collection's author later switches the backing storage to something without that operation, such as a TreeSet or a HashSet, every single piece of client code written against the old structure stops compiling or behaves incorrectly, even though the client never should have needed to know or care what the internal storage was in the first place. The Iterator pattern fixes this by giving client code a uniform hasNext()/next() contract instead, so the collection's author can change internal storage freely as long as the iterator's own logic is updated to match — client code using that contract never has to change.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to What's the difference between what the Facade pattern and the Adapter pattern are each trying to solve?← Back to all Low-Level Design & Design Patterns questions