[hibernate-dev] Returning Iterable

Sanne Grinovero sanne at hibernate.org
Fri Mar 6 05:01:09 EST 2015

I was already aware of that blog, and while he makes some interesting
observations, I strongly disagree on it being a general rule. Like
many of the people commenting on the blog post, and the author himself
admits the title was too broad ;-)

First of, it's an SPI that we consume ourselves. We *know* that all we
need is to iterate, and the "for each" idiom is all we need.
Exposing a List in this case was an error, as it's a leaky
abstraction: there is no ordering requirement, and in fact I was
hoping to replace the implementation with a Set but I couldn't do that
as we committed to a contract which exposes a List.

We all know the rules of encapsulation: expose the least possible, but
no less... obviously the blog poster has a point in his case as he was
bitten by the "no less" problem.
I guess we all like encapsulation of classes, or we could as well move
back to public static fields rather than accessors. And you all return
"Set", and not "HashSet" right? Even though I often prefer to keep the
private field to use the type of the concrete collection, as
*privately* it may be useful (that's a case by case call).

You expose the highest abstraction which satisfies the need, aiming at
a good balance of practicality for both the implementor of the
contract and the consumer.

There also is a performance aspect. By returning List or Set, decency
rules require me to wrap them in their immutable counterparts, or make
defensive copies.
But then when the collections' whole point is to actually mutate,
you'd need to do such a wrap (or such a copy) on a per-invocation of
the read.. even if you don't agree on it being a good enough
performance reason, it adds on the readability of the code.
Often that's not a big deal, still why do I need to pay for any cost
if its reason to be is completely moot.

Many of our internal contracts should be Iterable, especially if it's
only about iterating _some collection_.

It's different of course if you expose it as a domain model to a user
API: in that case you don't really know what the use case's practical
needs are going to need, and then like the blog states being able to
run "size()" is often too compelling.

On 6 March 2015 at 08:12, Emmanuel Bernard <emmanuel at hibernate.org> wrote:
> We had that debate in one of the PR. We ended up not returning it for other reasons.
> A small additional stone to the discussion is here http://alexruiz.developerblogs.com/?p=2519
> _______________________________________________
> hibernate-dev mailing list
> hibernate-dev at lists.jboss.org
> https://lists.jboss.org/mailman/listinfo/hibernate-dev

More information about the hibernate-dev mailing list