Whimusical
Whimusical

Reputation: 6629

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

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?

Upvotes: 4

Views: 2842

Answers (3)

GingerHead
GingerHead

Reputation: 8230

Well what you coded is partially right:

you need to test on some methods of the items like :

  1. size
  2. contains()
  3. get(index)
  4. exists()

So, you should rethink about your new architecture or override it with this method to take every-time what you need.

Upvotes: 0

helios
helios

Reputation: 13841

List, Set & Map are interfaces, so they're not tied to a particular implementation. So they are good candidates for returning types.

The difference between List/etc and Iterable/Iterator is the kind of access. One is for random access, you have direct access to all the data, and Iterable avoids the need for having all available. Ideal in cases where you have a lot of data and it's not efficient to have it all inplace. Example: iterating over a large database resultset.

So it depends on what you are accessing. If you data can be huge and must need iterating to avoid performance degradation, then force it using iterators. In other cases List is ok.

Edit: returning an iterator means the only thing you can do is looping through the items without other possibility. If you need this trade-off to ensure performance, ok, but as said, only use when needed.

Upvotes: 2

Louis Wasserman
Louis Wasserman

Reputation: 198033

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.

Upvotes: 3

Related Questions