What's the problem? π€
The null check process is properly one of the most tedious and boring things we have to do while writing Java code.
Why would I use null? isn't it a code smell? π€’
Since the introduction of Optional in Java we have a nice alternative to express the absence of a value instead using null.
However, most of the time we fix/add to other people's code, which most likely has null all over the place.
So, to deal with this issue we have to write a lot of code to check for nulls.
Example of null check π§
if (someVariable == null){
// do something
}
else{
// do something else
}
Solution Using Optional π€©
Optional provides us with a set of methods that allow to handle cases like
- If null return this value
- If null throw exception
- If null do calculation and return value
- If null run this function
- And a couple more...
Let's write some code to see how the first three work π
1οΈβ£
Null check style β οΈ
private String getString() {
String result = getStringFromDB();
if (result == null)
return "It's empty";
else
return result;
}
Optional style π
private String getStringWithTrick() {
return Optional.ofNullable(getStringFromDB()).orElse("It's empty");
}
2οΈβ£
Null check style β οΈ
private String getString() throws Exception{
String result = getStringFromDB();
if (result == null)
throw new Exception();
else
return result;
}
Optional Style π
private String getStringWithTrick() throws Exception{
return Optional.ofNullable(getStringFromDB()).orElseThrow(Exception::new);
}
3οΈβ£
Null check style β οΈ
private String getString() {
String result = getStringFromDB();
if (result == null)
return doCalculation();
else
return result;
}
Optional Style π
private String getStringWithTrick() {
return Optional.ofNullable(getStringFromDB()).orElseGet(this::doCalculation);
}
π If you want a formal intro to Java's Optional refer to my post How to escape NullPointerExceptions in Java using Optional.
Conclusion βοΈ
- We managed to write some clean/clear code to perform null checking using Optional instead of writing imperative checking.
Top comments (0)