Skip to main content

(How) can I improve null handling

Pl review the code below and suggest any improvements

package com.javahowdoi.challengeq;

public class GreetingTest {

    public static String greeting(boolean b) {
        if(b)
            return "Hello World!!!";
        else
            return null;
    }

    public static void main(String[] args ) {
        System.out.println( greeting(true) );
    }
}

Highlight ( Mouse click + drag ) the lines below for the answer:

Null handling can be improved by using Optional class.  greeting() method should return Optional <String> instead of returning a String.

public static Optional<String> greeting(boolean b) {
        if(b)
            return Optional.of("Hello World!!!");
        else
            return Optional.empty();
}
assertEquals( "Greeting match", "Hello World!!!", greeting(true).orElse("default greeting"));

Comments