Answer by Joshua Engel:
I like returningIterable
whenever I can, because it's immutable. When you return a Collection or a subclass of Collection, you risk having somebody modify an object that you had intended only for reference. Guava has a nice set of immutable collections, but it's not universal. Java has a collection of classes to create unmodifiable collections, but they're awkward because they still have an add method.Why don't more people do it? Partly, I think it's history. Iterable was only added in Java 5. That was some time ago, but the habit of using more concrete classes is established. Other parts of the API take collections where they should be taking Iterable. It's actually used very often implicitly, as the argument to afor
operator, but since it's implicit it's hard to see what's really going on. Plus, I think the fact that Iterable is a more awkward name than List or Set or Map doesn't make it all that attractive.When you do want a modifiable collection, it really does help to specify whether it's a Set or a List. The semantic distinction is crucial: if you're expected to modify it, you need to know the behavior of adding duplicates. So it'll be relatively rare that you want just any Collection without regard to that behavior, except in the case that you really should be using Iterable instead. Also, it's common for people to need Lists to have stable ordering and random access to elements, not just iteration, even if you're not going to modify it.It's heartening that people often do writeList<T> foo = new ArrayList<>()
, rather than mindlessly specifying the implementation of foo. That, at least, is better than nothing.So it would be nice ifComponent.getComponent
rather than an array (can you imagine what kind of dreadful things would happen if you modified that array?). That would set a better tone elsewhere in the system. ButIterable
joined the Java ecosystem too late, and while I use it, I'm not surprised that it doesn't see broader use.