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)