Iterable vs Iterator as a return behavior (Best Practice?)

collections, iterable, iterator, java, list

Solution

This would be a really bad plan.

I wouldn't say that 90% of the time you just use it in a for loop. Maybe 40-50%. The rest of the time, you need more information: `size`, `contains`, or `get(int)`.

Additionally, the return type is a sort of documentation by itself. Returning a `Set` guarantees that the elements will be unique. Returning a `List` documents that the elements will be in a consistent order.

I wouldn't recommend returning specific collection implementations like `HashSet` or `ArrayList`, but I would usually prefer to return a `Set` or a `List` rather than a `Collection` or an `Iterable`, if the option is available.

Problem

I´d just want to know your opinion regarding to change all the Collections function output to an Iterable type. This seems to me probably the most common code in Java nowadays, and everybody returns always a List/Set/Map in 99% of times, but shouldn´t be the standard returning something like ``` public final Iterable<String> myMethod() { return new Iterable<String>() { @Override public Iterator<String> iterator() {return myVar.getColl();} }; } ``` Is this bad at all? You know all the DAO classes and this stuff would be like ``` Iterable<String> getName(){} Iterable<Integer> getNums(){} Iterable<String> getStuff(){} ``` instead of ``` List<String> getName(){} List<Integer> getNums(){} Set<String> getStuff(){} ``` After all, 99% of times you will use it in a for loop... What dod you think?

Original source