Question

When should one consider implementing Iterable<T> as opposed to having a collection as an instance field? What are the benefits/consequences?

Was it helpful?

Solution

Implementing Iterable supports encapsulation. There is (usually) no need for the users of your class to know whether you are using a linked list or a hash table or what have you.

You could change the implementation details without having to modify any code that uses your class. Perhaps you want to switch between collections depending in the number of items, for instance.

You are also in control of what the user can and cannot do. If you give direct access to your collection then they may modify it without your knowledge, a very bad idea.

OTHER TIPS

The JavaDoc says it all:

Implementing this interface allows an object to be the target of the "foreach" statement.

Look at the implementors of the interface and it becomes clear when to use it. If you build your own collection (or 'something' a user should be able to iterate through), it makes sense to implement the interface. To conclude, in my experience in a 'simple, standard' application you will never implement your own Iterable.

I would use a more general interface wherever possible. As Iterable<T> is more general than List<T>, if the function's clients depend only the iterable interface (and not on list interface), I would prefer iterable. This allows a high possibility to later change the implementation would changing the interface.

The question is very general, so take this answer in the same spirit.

A common and popular tenet in object-oriented design is encapsulation and hiding implementation details. So if your container is a mere implementation detail of the class, it shouldn't be visible at all.

More generally, if you're considering exposing data members directly, then think twice. A well-designed class probably shouldn't just be handing things through to members. Rather, you want to give the class useful methods that describe the class's own semantics. Those may in turn use the internal container, but the container itself shouldn't be directly facing the user.

Finally, if your class itself has iterable semantics (which you will probably implement with an internal container), then by all means do give the class itself iterators. Iterators allow you to use generic algorithms and are a great way to make your class usable in a wide variety of settings. However, do be sure that the iterators traverse a range of semantically meaningful values. They might dig right into a member container, or they might do some additional processing and checking - in either way, the iterators should be yours, not just those of some member container.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top