0

When we use the Java 8 Optional feature, do we need to check the optional object itself is null before we call isPresent() ? see the 2nd line in my code below.

Optional<entity> optionalEntity = myRepository.findById(dao.getId());
if (optionalEntity != null) {  // is this check need?
    if(optionalEntity.isPresent() {
        MyEntity entityToUpdate = optionalEntity.get();
    }
 }
ever alian
  • 1,028
  • 3
  • 15
  • 45
  • 3
    Any API that returns a null `Optional` object is working hard to miss the point. And if you need to be that defensive in your code, then life is really hard. "No" *should* be the answer. – ernest_k Apr 19 '21 at 10:52
  • 1
    You never *need* to check anything for null if you are sure nobody ever uses null. If all devs follow some basic common sense practices (lets hope so) then no, you do not need to check the `optionalEntity` for null. If it ever crashes because `optionalEntity` is `null` track down whoever return `null` for an `Optional` and give them a good slap. – luk2302 Apr 19 '21 at 10:52

2 Answers2

3

No, you don't have to.

In theory, Optional<>s can be null but shouldn't be as the empty value would make more sense.

Returning a null Optional<> value is just bad API design.

Spring JPA uses Optional instead of null, just like it should do so you can skip the additional null check.

Also, using Optional#ifPresent indicates that you are using Optional incorrectly. You may want to use the other methods of Optional instead.

If you need to execute something if the Optional has a value, you can use the method Optional#ifPresent:

someOptional.ifPresent(value->doSomething(value));

This might not seem like a big advantage but it works well with other methods like Optional#map:

someOptional.map(value->value.getSomething()).ifPresent(value->doSomething(value))

Optional#map transforms the object in the Optional using the passed lambda expression.

Optional#filter replaces tte object in the Optional with null (empty Optional) if the object doesn't match the passed condition.

dan1st
  • 12,568
  • 8
  • 34
  • 67
  • 1
    why what is the problem of `isPresent() `? why suggest other methods? – ever alian Apr 19 '21 at 11:01
  • 1
    `isPresent()` is basically the same as a regular null-check on a nullable object. The purpose of `Optional<>` is to get away from this. – dan1st Apr 19 '21 at 11:03
  • can you pls update the answer then with which method to use? or the better approach? because some articles mentioned to use isPresent() – ever alian Apr 19 '21 at 11:04
1

Do I need to check the null for optional object itself before use?

No, either do not use an Optional<T>, or if you're using it, try not to get in a habit of checking optional instances against null, as this defeats the purpose of Optional<T>.

Remember, that:

  1. Optional<T> was not designed with an intention to swap null checks. It's a wrapper/container for a possibly existing object, nothing more, nothing less; therefore, in a lot of cases, it is just a nice, beautified and a concise alternative of boilerplate null-checks, with an addition, that you can chain activities, in just a line, when object is present;
  2. Optional<T> is not serializable.

Cay Horstmann nicely says, that:

The key to using Optional effectively is to use a method that either produces an alternative if the value is not present, or consumes the value only if it is present.

You can use ifPresent(Consumer<? super T> consumer) and if a value is present, you can chain some corresponding activity calls.

isPresent() can also be used, in some cases, and it returns boolean; you can then get() an instance, if it isPresent().

Additionally, you can find this useful.

Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66