DEV Community

Cover image for Clean Your Code Using Java Optional
Abdulcelil Cercenazi
Abdulcelil Cercenazi

Posted on

2

Clean Your Code Using Java Optional

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
}
Enter fullscreen mode Exit fullscreen mode

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;  
}
Enter fullscreen mode Exit fullscreen mode

Optional style 😍

private String getStringWithTrick() {  
    return Optional.ofNullable(getStringFromDB()).orElse("It's empty");  
}
Enter fullscreen mode Exit fullscreen mode

2️⃣

Null check style ☠️

private String getString() throws Exception{  
    String result = getStringFromDB();  
    if (result == null)  
        throw new Exception();  
    else  
     return result;  
}
Enter fullscreen mode Exit fullscreen mode

Optional Style 😍

private String getStringWithTrick() throws Exception{  
    return Optional.ofNullable(getStringFromDB()).orElseThrow(Exception::new);  
}
Enter fullscreen mode Exit fullscreen mode

3️⃣

Null check style ☠️

private String getString() {  
    String result = getStringFromDB();  
    if (result == null)  
        return doCalculation();  
    else  
     return result;  
}
Enter fullscreen mode Exit fullscreen mode

Optional Style 😍

private String getStringWithTrick() {  
    return Optional.ofNullable(getStringFromDB()).orElseGet(this::doCalculation);  
}
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ 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.

Check code on GitHub πŸ‘¨β€πŸ’»

Tiugo image

Fast, Lean, and Fully Extensible

CKEditor 5 is built for developers who value flexibility and speed. Pick the features that matter, drop the ones that don’t and enjoy a high-performance WYSIWYG that fits into your workflow

Start now

Top comments (0)

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay