One of the most useful things introduced by Java 8 is the Optional class (https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html). It is a container object that wraps either a value or null, to represent the absence of a value. You can quickly understand the benefits coming from it: a better way to handle the existence of null values with no need to explicitly check for nulls and possibly less chance to have NullPointerException exceptions. Some code like this
// The method call below could return null
User currentUser = getUser(id);
Role role = null;
if(currentUser != null) {
role = getRole(currentUser);
}
becomes:
Optional<User> currentUser = Optional.ofNullable(getUser(id));
Optional<Role> role = currentUser.map(u -> getRole(currentUser));
// The method call below could return null
User currentUser = getUser(id);
Role role = null;
if(currentUser != null) {
role = getRole(currentUser);
}
becomes:
Optional<User> currentUser = Optional.ofNullable(getUser(id));
Optional<Role> role = currentUser.map(u -> getRole(currentUser));
Comments
Post a Comment