DEV Community

Ansaf Ahmad
Ansaf Ahmad

Posted on

WTF is an Optional?

I'm starting a series of java tutorials that go along the title of WTF is a(n) _____ ? I'm going to start with optionals in this tutorial.

So WTF is an optional?

The Optional class was a class introduced in Java 8 and it was introduced to deal with null checks in streams. Even though it was introduced for streams, we can use it to create much cleaner null checks.

For example the following code will fail since no null checks were performed.

public class Main {
    // No null check is done here, a null pointer exception will be raised
    public static void main(String[] args) {
        System.out.println(printSecondWord("ONEWORD").toLowerCase());
    }

    // Return null if 2 words not there else return 2nd word
    private static String printSecondWord(String words){
        String[] wordsList = words.split(" ");
        return wordsList.length < 2 ? null : wordsList[1];
    }
}
Enter fullscreen mode Exit fullscreen mode

Before Java 8(you can do this now too), you had to do a manual null check like this:

public class Main {

    public static void main(String[] args) {
        String secondWord = printSecondWord("ONEWORD");
        if(secondWord != null) {
            System.out.println(secondWord.toLowerCase());
        }
    }

    // Return null if 2 words not there else return 2nd word
    private static String printSecondWord(String words){
        String[] wordsList = words.split(" ");
        return wordsList.length < 2 ? null : wordsList[1];
    }
}
Enter fullscreen mode Exit fullscreen mode

This way is fine but it does come with one issue that causes Null Pointer Exceptions a.k.a the Billion dollar mistake. The static method assumes that the other developer will do a null check. The main problem for traditional null pointer checks is that developers forget to do null checks and this can be problematic since one mistake can cause the whole application to fail.

A more modern way to structure the code and force the developer to do the null check is to return an optional

public class Main {

    public static void main(String[] args) {
        printSecondWord("ONEWORD").ifPresent(secondWord -> {
            System.out.println(secondWord);
        });

    }

    private static Optional<String> printSecondWord(String words){
        String[] wordsList = words.split(" ");
        return Optional.ofNullable(wordsList.length < 2 ? null : wordsList[1]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Returning an optional is a much better alternative since the developer has to manually access the result by callingifPresent from the static method. The optional.

Alternatively, you can also capture the boolean value of ifPresent and decide what to do.

import java.util.Optional;

public class Main {

    public static void main(String[] args) {
        Optional<String> secondWord = printSecondWord("ONEWORD");

        boolean isTheWordThere = secondWord.isPresent();
        // Print NOT HERE if not present
        if(!isTheWordThere){
            System.out.println("NOT HERE");
        }
        else{
            System.out.println(secondWord.get());
        }

    }
    // Return null if 2 words not there else return 2nd word
    private static Optional<String> printSecondWord(String words){
        String[] wordsList = words.split(" ");
        return Optional.ofNullable(wordsList.length < 2 ? null : wordsList[1]);
    }
}

Enter fullscreen mode Exit fullscreen mode

I hope this post will help you guys get started with optionals and you can explore more in depth with optionals in your projects.

Also since this is my first post, I would like some feedback and any comments are welcome!!

Keep on hacking!!!

Top comments (0)