Second try... Readable Collections Interfaces.
Carson Gross
carsongross at gmail.com
Thu Aug 4 06:09:57 UTC 2011
(This bounced or got hung up the first time I sent it.)
Hi Guys,
I work on Gosu, a JDK-based language, and I was talking w/ Charles Nutter
and Ola Bini today (ed: now last week) at OSCON, and a general idea that
I've been kicking around for a long time came up. They both didn't think it
was crazy, so I figured I'd bounce it off this mailing list. Apologies if
this has been discussed before.
Here's the problem I have: I'd like to return my mutable collections to
consumers as an immutable collection.
Now, I know I can wrap my collections in immutable versions, but that isn't
really what I want: I'm less concerned that the implementation is actually
immutable, but I'd like the consumer of my collections to *know* statically
that they aren't supposed to mutate the collection I'm handing them. Tt a
practical level, the wrapping approach necessitates me either wrapping the
mutable collection I've got in my class every time I return it or to
maintain a second reference to the wrapped class, both of which are ugly.
So, what I think I want is an interface like, for example, ReadableList,
which has only the readable methods on List and none of the mutators. And,
presumably, that would extend a ReadableCollection, which would have only
the readable methods on Collection, and so on. (One point that Josh Bloch
made was that Iterable breaks this, but I *think* you could introduce a
ReadableIterator interface without the remove() method and use covariance
return types in the mutable collections to make it all work out.) I could
then return my mutable Lists as this interface, and send a strong signal to
the caller that they shouldn't mutate them. (If they downcast... hey, we
are all adults here, right?)
Some sample code:
class MyClass {
List<String> someNames = ...
public ReadableList<String> getSomeNames() {
return someNames;
}
}
So callers of MyClass#getSomeNames() will know that I don't intend for them
to mutate the list. And, of course, it would be nice if these interfaces
worked properly with the for() statement, etc.
As a side note, I like the name ReadableList vs. the more obvious
ImmutableList, since java.util.List would extend this interface and it isn't
an ImmutableList.
Anyway, this is obviously a very rough idea, but I'd like to hear what
people think and what problems might come up when implementing it.
Thanks,
Carson
More information about the core-libs-dev
mailing list