Has it been considered to add inverse methods to collections which are in Optional?
Dave Franken
dwfranken at gmail.com
Tue Dec 8 12:17:25 UTC 2020
Dear all,
The class java.util.Optional could be considered a collection with a limit
on how many values it can hold, minimum 0, maximum 1.
Likewise, any class implementing the regular java.util.Collection has a
minimum, 0 and a maximum > 1.
While Optional does not implement Collection, it could be seen as a
pseudo-collection in this regard.
Optional has a convenience method for which there is an inverse,
isPresent() which is the inverse of isEmpty().
Has it been considered to add such a method (or other convenience methods)
to collections as well?
For instance, java.util.Collection has the method isEmpty() which behaves
exactly like Optional's isEmpty(), but it does not have an inverse
counterpart.
I think it would be logical to add such as convenience method to
Collection, because we have a precedent with Optional.
We could add `bikeshed name here, as an example I'm going to use
hasElements()' to java.util.Collection and, for simplicity's sake make the
default implementation just call !isEmpty(); obviously implementations
could offer optimized versions if necessary.
It would improve readability where we have the negation of isEmpty(), e.g.:
if (!myList.isEmpty()) {
}
// vs.
if (myList.hasElements()) {
}
Note that in the first example, which is the current way of checking
whether a (non null) collection has any elements, the negation and the
method it negates are separated by the variable name.
If the variable would instead be another method call or any other, longer,
expression, this would make the example even less readable as the negation
and final method call are further apart.
The second example has the advantage of more clearly expressing the intent
of the user - which is to check if the collection has any elements.
Moreover, it offers matching functionality for something which already
exists in the JDK core libs, Optional's isPresent().
If this has already been discussed and dismissed, I'm sorry for bringing it
up again and if anybody could point me to the conclusion and the reasoning
behind it, I would be grateful.
Kind regards,
Dave Franken
More information about the core-libs-dev
mailing list