Video in progress
In internal libraries and service interfaces, which do you make the standard return type for methods: List, Collection, Iterable or Stream?
The return type is a contract: it says what is being promised to the caller. I usually make List the standard (it has order and size and can be iterated many times), Stream only for lazy or very large data, and I almost never use Iterable.
📖 Answer
What each type promises:
Collection: has a size, can be iterated many times, order unknown. It says little, so you have a lot of freedom to swap the implementation.List: order and index. 90% of callers expect exactly this:get(0),size(), serialization to JSON.Set: a uniqueness guarantee. If that is what you want to say, don't return aList.Iterable: iteration only. There is nosize()and no Stream. The caller almost always turns it into a list right away.Stream: one-shot, lazy. Good for large or unbounded data, but if it is tied to a resource (a DB cursor, a file), the caller has to callclose(), and they forget.
// Spring Data: if it returns a Stream, you must use it inside a transaction and with try-with-resources
try (Stream<Order> s = repo.streamAllByStatus(PAID)) {
s.forEach(exporter::write);
}
My standard:
- The usual result is
List<T>, immutable, never null. - If it has uniqueness semantics,
Set<T>. - For cases like a million-row export, a separate method with a distinct name (
streamAll...) and the duty to close documented. Or, even safer, a callback:forEachOrder(Consumer<Order>), where the library manages the resource itself. - If you need pagination,
Page<T>/Slice<T>or your own type with a cursor.
The important part at the Staff level is consistency. If one module has Collection, another Iterable and a third an array, then every integration gets conversion code and copies. That is why the rule is written in the API style guide and checked in API review.
Sign up to mark studied questions and save your progress.