When to use Java 8 Optional instead of traditional null pointer check ?

My project has recently moved to Java 8. Now, I see applications flooded with
Optional objects mainly to check the Null Pointer on an object.

Before Java 8  code style to check the null pointer
Employee employee = employeeServive.getEmployee();
if(employee!=null){
    System.out.println(employee.getId());
}


After java 8  code style to check the null pointer
Optional<Employee> employeeOptional = Optional.ofNullable(employeeService.
getEmployee());
// Another way of implementing above  where service itself will return
Optional<Employee> employeeOptional = employeeService.getEmployee();
if(employeeOptional.isPresent()){
    Employee employee = employeeOptional.get();
    System.out.println(employee.getId());

}

Which one is better to check Null Pointer
I see  style 1 is better when intention is just to check Null Pointer.
So I find, style 1 is more clear and lesser lines of code. In this case
I see devs are overusing it probably they learnt something new and try
that or they think new API is always good irrespective what it is offering.
Though it can be helpful in a sense where caller gets Optional<Employee>
from  service as it gives him/her better hint/signal to check the null pointer.

Use cases when Optional is advantageous to use

There are couple of scenarios when it can be useful
  1. Optional class provides various methods where if value is present
    then apply the functional interface  like below

    ifPresent(Consumer<? super T> consumer)
    map(Function<? super T,? extends U> mapper)
    flatMap(Function<? super T,Optional<U>> mapper)
    filter(Predicate<? super T> predicate)

    In Employee example it can be
    employee.ifPresent(e -> System.out.println(e.getId()));
  2. Also wrapping the legacy(like service developed before java 8) object
    around wrapper is really helpful in below scenario where we need to 
    execute the service method if value is present

    Optional.of(employeeService).map(EmployeeService::getEmployee)
    .map(Employee::getId).ifPresent(System.out::println);
I have the consolidated my research here from my question at this forum and other sources on google

Comments

Popular posts from this blog

How to solve javax.net.ssl.SSLHandshakeException ?

What is REST actually?