I find myself agreeing to return an interface instead of a concrete class.
The reason is simple, I want loose coupling.
But will there be other implications or trade offs?
It's best to return the most generic type that's appropriate for your interface. Save this answer. Show activity on this post. For types like List or ArrayList there shouldn't be any complication and you should return List promoting code to an interface.
The List is an interface, and the ArrayList is a class of Java Collection framework. The List creates a static array, and the ArrayList creates a dynamic array for storing the objects. So the List can not be expanded once it is created but using the ArrayList, we can expand the array when needed.
It depends on what guarantees you want to provide the user. If the data is sequential such that the order of the elements matter and you are allowing duplicates, then use a list. If order of elements does not matter and duplicates may or may not be allowed, then use a collection.
It's preferable to do this because it makes your code more resilient to changes in the implementation. If for some reason it was decided that a different List implementation should be used, code that was programmed to the List interface would not need to be changed extensively.
It's best to return the most generic type that's appropriate for your interface.
If there's some reason why ArrayList
is inherently appropriate for the data you're returning then you should use that. Typically List
is fine but you might also consider using Collection
if the returned values are inherently unordered:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With