Reputation: 239
Suppose I have this layout:
public void caller(@NonNull List<Integer> param){
// param COULD BE EMPTY, but it CANNOT be NULL, its not nullable
if(!param.isEmpty()) function(Optional.of(param));
// If param is empty then just dont call "function"
}
public void function(Optional<List<Integer>> someParam){
someParam.ifPresent(...);
}
Here is the question: Is not creating an Optional
based on an empty list correct usage? The confusion I am having is whether we should be providing an Optional regardless if param
in caller
is empty or not because it is not null, but I am wondering if this is the right usage?
Upvotes: 1
Views: 9705
Reputation: 26046
someParam.ifPresent(...);
the body of ifPresent
is always invoked, because there always is an element, even if it's an empty list (you're checking for nullity @NonNull List<Integer> param
).Optional.of
instead of Optional.ofNullable
, so there is always going to be a non-null element.Optional
does not make much sense, why not passing an empty list and not processing any elements?if(!param.isEmpty())
is redundant, because you know there are elements in the list, as stated in 3. why not passing the list for processing?tl;dr: You're mixing an empty list with null
, wrapping any collection in Optional
does not make much sense.
Upvotes: 3