Handle Null like a pro using Optional
Chaitanya Chunduri
Posted on August 16, 2021
Many times we think that our code is perfect, works like a charm in the given scenarios and we proceed for deployment in production on a fine Friday. But when the code hits production due to unexpected data or due to some failure, when the code throws NullPointerExcpetion, the feeling comes like damn this weekend also ha...
But Thank God, we have a rescuer to fight with NPE(NullPointerException) who came into the existence since Java 8 which is Optional class.
In this article let us find out how we can use Optional in day to day jobs.
To create Optional object we have two methods,
- using of method
- using ofNullable
Here are the examples
Optional<String> optional = Optional.of("Chaitanya");
Optional<String> opNullable = Optional.ofNullable("Chaitanya");
If you think that there is a possibility of null coming because of the calling function then you can use ofNullable.
of method throws NPE if the value is null, so, if you're certain that you don't get a null value you can use of method.
IMO, for simple operations like variable initialization or you've simple values and you want to pass them then you can use of method, if you're calling some external function for the result then you can use ofNullable.
Optional is something like a container that holds a value. To get things out of the container we need to open it, same way to get the value out of the Optional, we've get method.
Optional<String> optional = Optional.of("Chaitanya");
System.out.println(optional.get());
Think that you got a big container, you opened it and found nothing, then you feel disappointed right? To save from these kinds of bad feelings, we have isPresent method, usage is like this.
Optional<String> nameOptional = getFirstName();
if(nameOptional.isPresent()) {
System.out.println(nameOptional.get());
} else {
System.out.println("No Name :( ");
}
If you want to handle in a functional style, here is the way
nameOptional.ifPresent(value -> {
System.out.println(value);
});
or using method references
nameOptional.ifPresent(System.out::println);
Sometimes we don't want to do anything when an exception raises, without Optional one way is we return null in catch block, but from Optional we've one more method empty(), here is the usage:
try {
return Optional.ofNullable(getEmpName());
} catch (Exception ex) {
return Optional.empty();
}
Sometimes we may need to manipulate the results of certain operations, in such cases, we've map and flatMap methods
Optional<String> nameInUpperCaseOptional =
Optional.ofNullable(getEmpName())
.map(String::toUpperCase)
.get();
Here map returns one more Optional object with the transformed value. If you want to get direct value instead of Optional object, then you can use flatMap method.
String nameInUpperCase = Optional.ofNullable(getEmpName())
.flatMap(String::toUpperCase);
If you want to return a default value when there is no value present, you can use orElse
String EMPTY = "";
String name = Optional.ofNullable(getEmpName())
.orElse(EMPTY);
If you want to perform some action when there is no value present, you can use orElseGet
String name = Optional.ofNullable(getEmpName())
.orElseGet(_ -> System.out.println("There is no Value :( "));
If you want to throw an exception when there is no value present then we've orElseThrow
String name = Optional.ofNullable(getEmpName())
.orElseThrow(Exception::new);
In Java 11, There are some more enhancements in Optional class like ifPresentElse, or, stream, here is the link to documentation for further details. Java 11#Optional
That is it for this article :) If you use Optional properly you can pretty much avoid NPE and can avoid stressful weekends too.
Thanks for spending time. I appreciate your feedback.
Posted on August 16, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.