NPE throwing behavior of immutable collections
Kasper Nielsen
kasperni at gmail.com
Mon Jan 30 10:23:34 UTC 2023
On Mon, 30 Jan 2023 at 09:11, Glavo <zjx001202 at gmail.com> wrote:
> Now that we have the interface default method, can we add a new method to the Collection to obtain the support status of the feature, like this:
>
> public record CollectionFeature(String name) {
> public enum Status {
> SUPPORTED, UNSUPPORTED, UNKNOWN
> }
> }
>
> public interface Collection<E> extends Iterable<E> {
> CollectionFeature ADD_ELEMENT = new CollectionFeature("ADD_ELEMENT");
>
> // ...
>
> default CollectionFeature.Status supports(CollectionFeature feature) {
> return UNKNOWN;
> }
> }
>
> public interface List<E> extends Collection<E> {
> CollectionFeature RANDOM_ACCESS = new CollectionFeature("RANDOM_ACCESS");
> CollectionFeature UPDATE_ELEMENT = new CollectionFeature("UPDATE_ELEMENT");
>
> // ...
>
> @Override
> default CollectionFeature.Status supports(CollectionFeature feature) {
> if (feature == RANDOM_ACCESS)
> return this instanceof RandomAccess ? SUPPORTED : UNSUPPORTED;
> else
> return UNKNOWN;
> }
> }
>
>
> Is there anything preventing us from doing this?
Not anything other than this is a solution looking for a problem.
What are you going to do with this information at runtime? Not insert the
element in a collection if it doesn't support Update? In 99% of all cases,
this is a failure scenario, and you will want to throw an exception. Which
Collection#add() will do for you by throwing an
UnsupportedOperationException.
RandomAccess you can check by instanceof java.util.RandomAccess
And best you could use such a feature for debugging. Instead, just print out
the class name and go read the Javadocs for the class.
And if you are going to support this for Collection, people also want this for
queues, map, sets, etc. Further complicating a Collection API that is already
complex enough.
/Kasper
More information about the core-libs-dev
mailing list