Question

Effective java encourages use to interfaces rather than abstract / concrete classes. Question is if there is an interface heirachy, which interface type should be chosen and why ?

For example, an ArrayList implements List which implements Collection which implements a Iterable. So when do we pass a list vs collection vs iterable ?

Obvious answer is that each subclasses keep adding more functions. So should we keep climb up the hierarchy until the required functionality is matched ? I mean if in an imaginary application only iterator() is needed then use Iterable else use List ?

Was it helpful?

Solution

Always use the most abstracted interface that fulfills your needs.

In the example of Iterable, Collection, List, if you only need to iterate then only pass around an Iterable. If you only need methods provided by Collection then only pass around a collection.

The reason for this is so that you can easily replace later.

For example, if you have a function that only needs an Iterable but takes a List as a function parameter, then later if you decide that it makes more sense to store your data as a HashSet you have to change a lot of code to make it work. However, since HashSet is Iterable, if you had just passed an Iterable to your function originally you would have had to change much less code.

It also makes testing easier in some cases. For example, Imagine you have some interface Foo that extends interface Bar. If you have a function that takes a Foo parameter then you have to mock everything that Bar expects and you have to mock everything that Foo adds onto that. If your function only expected a Bar parameter then you only have to mock Bar.

OTHER TIPS

It is clear, from his comments, that OP wanted all along to go for "most abstract", and normally I'd agree.

But, in my practical experience, size() is really really useful. (joke omitted). And often becomes more useful as your code evolves. So, to plan ahead, my suggestion, in this specific example, is to go with Collection over Iterable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top