Optional: Invalid (i) .ifPresent ... vs if (i! = Null)

I recently saw a post ( on @java twitter ) that suggests the following code is becoming more common:

Optional.ofNullable(i).ifPresent(x -> doBlah(x));

instead:

if (i != null) {
  doBlah(i);
}

Using Optional in this case seems to me very inconvenient, even ignoring the names of variables - the latter is easier to read and more idiomatic for use (it processes zeros). I believe that this also improves semantics - I most likely come from code that does not adhere to the semantics that Option is trying to capture (as described in a possible duplication and in this Oracle article ).

I do not see one, but is there a good semantic reason to prefer optional access. Optional approach (ignoring the performance impact that may have depending on how it is used)?

+4
source share
1 answer

For the same code block, it makes no sense to wrap a potentially null object in an optional one just for calling ifPresent()on it.

API, , . . API , ifPresent() , , .

+9

Source: https://habr.com/ru/post/1669997/


All Articles