Wednesday

Some advices on using Optional

//DON'T
Optional<User> user = null;
//DO
Optional<User> user =  Optional.empty();

//Don't confuse Optional.of() and Optional.ofNullable(). Choose the right one.

//DON'T
return Optional.ofNullable("EDA");
//DO
return Optional.of("EDA"); //no risk for NPE of using of() method so choose this.

//DON'T
String parameterToMethod = ...; // can be null
return Optional.of(parameterToMethod);//can throw NPE if parameter is null
//DO
String parameterToMethod = ...; // can be null
return Optional.ofNullable(parameterToMethod);//no risk for NPE

//DON'T
String userName = ... ;
return Optional.ofNullable(userName).orElse("EDA");
//DO
String userName = ... ;
return userName == null ? "EDA" : userName; // choose always the simplest one for such easy cases

//DON'T
Optional<String> user = ...; //can be empty
String myUser = user.get(); // can throw NoSuchElementException if user is empty
//DO
Optional<String> user = ...; //can be empty
if(user.isPresent()) {
 String myUser = user.get();
}


//DON'T
Optional<String> userName = ...;
if(userName.isPresent()) {
   return userName.get();
} else {
   return "Unknown person";
}
//DO
Optional<String> userName = ...;
return userName.orElse("Unknown person");

// DON'T
Optional<String> parameterUserName = ... ;
Optional<String> userName = Optional.of("EDA");
if(parameterUserName.isPresent()) {
 return parameterUserName;
} else {
 return userName;
}
//DO
Optional<String> parameterUserName = ... ;
Optional<String> userName = Optional.of("EDA");
return parameterUserName.or(() -> userName); // with java 9

// DON'T
Optional<String> userName = ... ;
if(userName.isPresent()) {
    System.out.println("userName: " + userName.get());
} else {
    System.out.println("User not found");
}
//DO - java 9
Optional<String> userName = ... ;
userName.ifPresentOrElse(
    System::out::println, 
    () -> System.out.println("User not found")
};

//DON'T
Optional<String> userName = ...;
if (userName.isPresent()) {
    System.out.println("userName: " + userName.get());
}
//DO
Optional<String> userName = ...;
userName.ifPresent(System.out::println);

//DON'T
Optional<String> userName = ...;
if(userName.isPresent()) {
 return userName.get();
} else {
 throw new NoSuchElementException(); 
}
//DO
Optional<String> userName = ...;
return userName.orElseThrow(); //java 10
return userName.orElseThrow(YourException::new);//java 8-9 

//DON'T
 .......
 .filter(Optional::isPresent)
        .map(Optional::get)
 .collect(toList());
//DO
 .......
 .flatMap(Optional::stream)
 .collect(toList());

// AVOID
Optional<Integer> opt = Optional.of(10);
Optional<Long> opt = Optional.of(20L);
Optional<Double> opt = Optional.of(20.53d);

// PREFER
OptionalInt opt = OptionalInt.of(10);           // opt.getAsInt()
OptionalLong opt = OptionalLong.of(20L);        // opt.getAsLong()
OptionalDouble opt = OptionalDouble.of(20.53d); // opt.getAsDouble()

No comments:

Post a Comment