jjot0
jjot0

Reputation: 239

Providing an Empty List to an Optional?

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

Answers (1)

Andronicus
Andronicus

Reputation: 26046

  1. 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).
  2. You're using Optional.of instead of Optional.ofNullable, so there is always going to be a non-null element.
  3. Wrapping list in Optional does not make much sense, why not passing an empty list and not processing any elements?
  4. 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

Related Questions