Why aren’t java.util.Collection and java.lang.Iterable more popular as types for variables and method return values?

Answer by Joshua Engel:

I like returning

Iterable

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 a

for

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 write

List<T> foo = new ArrayList<>()

, rather than mindlessly specifying the implementation of foo. That, at least, is better than nothing.

So it would be nice if

Component.getComponent

returned an

Iterable

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. But

Iterable

joined the Java ecosystem too late, and while I use it, I'm not surprised that it doesn't see broader use.

Why aren't java.util.Collection and java.lang.Iterable more popular as types for variables and method return values?

Advertisements

Leave a comment

Filed under Life

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s