Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to return Iterable<String> rather than List,Set,Collection?

Tags:

java

neo4j

So I have been working fairly extensively with the Neo4j API, and I have noticed that virtually always they will have functions which return

Iterable<Class>

whereas I have always understood that it is better to return one of Set, List, or Collection unless one has a compelling reason to do otherwise. Set to indicate to the user that it will never have duplicate elements, List when order is important or it contains duplicates, or Collection when you don't have a policy.

I prefer these to Iterable as they have useful utilities like .contains(), .add() etc. I have found that very often I have to write code to convert an Iterable to a Collection.

So my question is: Am I missing something important? Is there a sound reason to use Iterable over Collection? When would you do so? Obviously, the guys at Neo4j seem to be first rate programmers, so I assume that they have a reason for this, but I cannot see it.

like image 979
phil_20686 Avatar asked Jul 14 '14 14:07

phil_20686


1 Answers

That is simply saying that they're giving you something to iterate over. They're not making any promises about what's implemented under the covers.

In particular, there may not be a real collection class behind this. The elements may be evaluated and/or fetched lazily as you iterate over them (imagine how you could possibly return a collection of, say, 100M elements). In that case, you'd better be careful collecting all the elements into a reified collection, since it's going to be pretty sizeable.

Since Neo4J is a graph database, that makes sense. It's analogous to a JDBC ResultSet, in which you don't get a collection of results, but rather row-by-row, and if you really want to hold all the results, you have to explicitly create a collection yourself.

like image 83
Brian Agnew Avatar answered Nov 15 '22 10:11

Brian Agnew