New Collection framework?

Stanislav Baiduzhyi sbaiduzh at redhat.com
Wed Feb 10 11:17:48 UTC 2016


On 10/02/16 05:03, David Holmes wrote:
>> * The main Collection interface allowes too much. If you get a
>> Collection and
>> you should not modify it, your programm will either behave stragly
>> with a hard
>> to detect bug, or crash with some kind of
>> UnsupportedOperationException, when
>> you do it.
>> I have my problems with UnsupprtedOperationException, because when i
>> get a
>> Collection, i have to read the documentation (if existing) to know
>> what i am
>> allowed to do, or run unexpectedly into an exception. Would it be
>> great to
>> hava an "readonly" interface, which simply does not have and modifing
>> methods?
>
> I don't understand your problem. If you write a method that takes a
> collection then your method has a specification as to what it does that
> involves the collection that is passed in. If the passed in collection
> doesn't in fact support that then the UnsupportedOperationException
> propagates back to the caller that passed you an inappropriate
> collection - and that's exactly as it should be. If you take a
> collection and then try to do something to it that you didn't specify
> you were going to do, and get UnsupportedOperationException then that is
> a bug in your code - if you let it propagate then your caller gets it
> and the user of your code submits a bug report.
>
> In case you have not seen it there is a document that discusses the
> design of the Collections framework and why the existing approach was
> taken:
>
> https://docs.oracle.com/javase/8/docs/technotes/guides/collections/designfaq.html

No that's little different. I've had similar issues on multiple 
projects. When you want to keep your DTOs immutable, you have to either 
return a copy of collection in getter or wrap it into unmodifiable. 
Unmodifiable is not visible on API level but behaves differently on 
implementation level, making it harder to support. So many projects are 
just returning Guava ImmutableList or similar, to make it obvious on API 
level that this collection should not be modified.

So yes, you are correct that it is documented and not an issue of JDK. 
Yet it is a valid issue of API design, having something like 
ImmutableList on API level would make it much simpler to follow 
self-documenting code principles and would improve maintenance cost in 
general.

It would be very helpful to have a Collection extending some kind of 
ReadOnlyCollection (and similar to List and Set) that has only read 
operations, but probably that is not doable in backward-compatible manner.

-- 
Regards,
     Stas



More information about the core-libs-dev mailing list