class MyCollection {
Items menuItems;
...
public Iterator createIterator() {
return new Iterator(menuItems);
}
}
class Client {
public someMethod() {
Iterator iterator = collection.createIterator();
while(iterator.hasNext()) { //doSomething }
// Client is calling iterator's method directly
}
}
above is a simple iterator pattern.
I wonder does Client violates the principle of least knowledge.
Is it inevitable to violate the principle in iterator pattern?
Technically the Client does violate the Law as the object(iterator) is neither an instance variable nor a passed argument. However a Collection being a pure data structure they are exempt from this law Law of Demeter with data model objects