Iterators - a solution looking for a problem?

I just read the Xojo blog on making your class iteratable - see https://blog.xojo.com/2017/12/13/make-your-own-classes-iterables/ - and at the end the code is

For Each s As PostalAddress In p Listbox1.AddRow s.street + ", " + s.streetNumber.ToText + " Piso: " + s.streetFlat.ToText Next

Which I find weird in the first place. Find a postal address in a person? Horrible image comes to mind. But I disgress.

Couldn’t you just forget about making the class iteratable and simply iterate over the array directly?

For Each s As PostalAddress In p.PostalAdresses Listbox1.AddRow s.street + ", " + s.streetNumber.ToText + " Piso: " + s.streetFlat.ToText Next

In other words: is being able to make your own class iteratable a solution looking for a problem? Are there any good usage scenarios?

Large parts of my app work with iterators. There are lists of things and you simply work through them. It doesn’t matter what they are. As usual the example isn’t very good.

I have mailboxes to archive. Could be from a mail client or an imap account. The iterator knows how to pick the next item. The items know what to pick. So the iterators make more sense if you have several different classes implementing the same interface.

Hi Markus,

Maybe not the best example (sometimes it’s not easy to pick an example with no much code)… but it was more about the concepts than the example. I think Iterators are a good solution.

Javier

Iterators area really useful. Like a lot of things in programming they are not the ONLY way to do it.

A class might contain an array and additional data which must remain synchronised to the array in some way.

It is not good for objects of this class to expose the array directly through a public method or property, because outside code would then be able to append or remove from the array without the class’s knowledge, possibly putting the object into an inconsistent state.

Using iterators and operator overloading allows the class to provide an array-like interface which is read-only to outside code, but which retains benefits such as compatibility with ‘for each’.