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 ‍

原文链接:Clean Your Code Using Java Optional

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容