Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4536

Convert Null Value to a Default Value in Java

$
0
0

1. Overview

In 1965, Tony Hoare introduced the concept of a null reference. Since then, countless hours have been spent reading the logs and trying to find the source of NullPointerExceptions. This exception is so ubiquitous that it’s common to refer to it as NPE.

In this tutorial, we’ll learn how to mitigate this problem. We’ll review several techniques that simplify converting nulls to default values.

2. Simple if Statements

The easiest way to approach the conversion is to use if statements. They’re basic language structures and benefit from being clear to developers with different experiences and levels. The best part of this approach is that it’s verbose, which simultaneously is the worst part:

@ParameterizedTest
@ArgumentsSource(ObjectsProvider.class)
void givenIfWhenNotNullThenReturnsDefault(String givenValue, String defaultValue) {
    String actual = defaultValue;
    if (givenValue != null) {
        actual = givenValue;
    }
    assertDefaultConversion(givenValue, defaultValue, actual);
}

Because we have total control over the logic, we can easily change, extract, and reuse it. Additionally, we can make it lazy if we want:

@ParameterizedTest
@ArgumentsSource(ObjectsSupplierProvider.class)
void givenIfWhenNotNullThenReturnsDefault(String givenValue, String expected, Supplier<String> expensiveSupplier) {
    String actual;
    if (givenValue != null) {
        actual = givenValue;
    } else {
        actual = expensiveSupplier.get();
    }
    assertDefaultConversion(givenValue, expected, actual);
}

If the operations are quite simple, we can use a ternary operator to make them more inlined. The Elvis operator didn’t make it into Java, but we still can improve the code:

@ParameterizedTest
@ArgumentsSource(ObjectsProvider.class)
void givenTernaryWhenNotNullThenReturnsDefault(String givenValue, String defaultValue) {
    String actual = givenValue != null ? givenValue : defaultValue;
    assertDefaultConversion(givenValue, defaultValue, actual);
}

Also, it allows a lazy approach as only the required expressions are evaluated:

@ParameterizedTest
@ArgumentsSource(ObjectsSupplierProvider.class)
void givenLazyTernaryWhenNotNullThenReturnsDefault(String givenValue, String expected, 
  Supplier<String> expensiveSupplier) {
    String actual = givenValue != null ? givenValue : expensiveSupplier.get();
    assertDefaultConversion(givenValue, expected, actual);
}

We can extract this logic into a separate method with a good name to make our code more readable. However, Java and some external libraries have done it already.

3. Java Objects

Java 9 provides us with two utility methods: Objects.requireNonNullElse and Objects.requireNonNullElseGet. These methods have implementations similar to those we reviewed. Overall, they provide a better API and make the code self-explanatory:

@ParameterizedTest
@ArgumentsSource(ObjectsProvider.class)
void givenObjectsWhenNotNullThenReturnsDefault(String givenValue, String defaultValue) {
    String actual = requireNonNullElse(givenValue, defaultValue);
    assertDefaultConversion(givenValue, defaultValue, actual);
}

Static imports can help us remove the Objects class name to reduce the noise. The lazy version looks like this:

@ParameterizedTest
@ArgumentsSource(ObjectsSupplierProvider.class)
void givenLazyObjectsWhenNotNullThenReturnsDefault(String givenValue, String expected,
  Supplier<String> expensiveSupplier) {
    String actual = requireNonNullElseGet(givenValue, expensiveSupplier);
    assertDefaultConversion(givenValue, expected, actual);
}

However, this API is accessible starting only from Java 9. At the same time, Java 8 also provides some convenient tools to achieve a similar result.

4. Java Optional<T>

The main idea behind the Optional<T> class was to fight the issue with null checks and NullPointerExceptions. It’s possible to identify nullable APIs in documentation, but a better solution is to show it explicitly in the code. Getting an Optional<T> from some method unambiguously tells us the value might be null. Also, IDEs can use static analysis for notifications and highlighting.

Explicit null checks weren’t the goal of this class. However, we can use it to wrap a value we would like to check and do some operations over it:

@ParameterizedTest
@ArgumentsSource(ObjectsProvider.class)
void givenOptionalWhenNotNullThenReturnsDefault(String givenValue, String defaultValue) {
    String actual = Optional.ofNullable(givenValue).orElse(defaultValue);
    assertDefaultConversion(givenValue, defaultValue, actual);
}

The lazy version looks quite similar:

@ParameterizedTest
@ArgumentsSource(ObjectsSupplierProvider.class)
void givenLazyOptionalWhenNotNullThenReturnsDefault(String givenValue, String expected,
  Supplier<String> expensiveSupplier) {
    String actual = Optional.ofNullable(givenValue).orElseGet(expensiveSupplier);
    assertDefaultConversion(givenValue, expected, actual);
}

Creating a separate wrapper object for a null check might be questionable. At the same time, it might be useful for reaching through data objects without chained null checks:

@Override
public Delivery calculateDeliveryForPerson(Long id) {
    Person person = getPersonById(id);
    if (person != null && person.getAddress() != null && person.getAddress().getZipCode() != null) {
        ZipCode zipCode = person.getAddress().getZipCode();
        String code = zipCode.getCode();
        return calculateDeliveryForZipCode(code);
    }
    return null;
}

We can do the same, but using Optional.map(Function<T, U>):

public Delivery calculateDeliveryForPerson(Long id) {
    return Optional.ofNullable(getPersonById(id))
      .map(Person::getAddress)
      .map(Address::getZipCode)
      .map(ZipCode::getCode)
      .map(this::calculateDeliveryForZipCode)
      .orElse(null);
}

Wrapping objects in Optional<T> early on can reduce the checking we must do later.

5. Guava Library

We can import Guava to get a similar functionality if all the previous methods aren’t suitable, for example, when using earlier versions of Java. Let’s start by adding the dependency:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>33.0.0-jre</version>
</dependency>

It mirrors the Java functionality and doesn’t add any explicitly useful features. To get a default value if the provided is null, we can use MoreObjects:

@ParameterizedTest
@ArgumentsSource(ObjectsProvider.class)
void givenGuavaWhenNotNullThenReturnsDefault(String givenValue, String defaultValue) {
    String actual = MoreObjects.firstNonNull(givenValue, defaultValue);
    assertDefaultConversion(givenValue, defaultValue, actual);
}

MoreObjects replaces the Guava’s Objects utility class, which was deprecated and planned for removal. However, it doesn’t allow the default value to be supplied lazily. Also, it provides an Optional<T> class with the same name as Java but resides in a different package:

@ParameterizedTest
@ArgumentsSource(ObjectsProvider.class)
void givenGuavaOptionalWhenNotNullThenReturnsDefault(String givenValue, String defaultValue) {
    String actual = com.google.common.base.Optional.fromNullable(givenValue).or(defaultValue);
    assertDefaultConversion(givenValue, defaultValue, actual);
}

We can also implement a chain of modifications using this class as well:

@Override
public Delivery calculateDeliveryForPerson(Long id) {
    return Optional.fromNullable(getPersonById(id))
      .transform(Person::getAddress)
      .transform(Address::getZipCode)
      .transform(ZipCode::getCode)
      .transform(this::calculateDeliveryForZipCode)
      .orNull();
}

However, the transform method doesn’t allow null-returning functions, and we can receive the following exception message:

java.lang.NullPointerException: the Function passed to Optional.transform() must not return null.

Guava is a good substitution for Java features if they’re unavailable, but it provides less functionality than Java Optional<T>.

6. Apache Commons

Another library we can use to simplify our null checks is Apache Commons. Let’s add dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

However, it provides only simple methods to get the first non-null value out of several arguments:

@ParameterizedTest
@ArgumentsSource(ObjectsProvider.class)
void givenApacheWhenNotNullThenReturnsDefault(String givenValue, String defaultValue) {
    String actual = ObjectUtils.firstNonNull(givenValue, defaultValue);
    assertDefaultConversion(givenValue, defaultValue, actual);
}

The lazy version is a little bit inconvenient API, as it requires Supplier<T>, so we’ll have to wrap a value if we already have one:

@ParameterizedTest
@ArgumentsSource(ObjectsSupplierProvider.class)
void givenLazyApacheWhenNotNullThenReturnsDefault(String givenValue, String expected,
  Supplier<String> expensiveSupplier) {
    String actual = ObjectUtils.getFirstNonNull(() -> givenValue, expensiveSupplier);
    assertDefaultConversion(givenValue, expected, actual);
}

Overall, this is also a nice substitution for Java features if they’re not accessible to us for any reason.

7. Conclusion

NullPointerException is the most common exception developers face. There are several convenient ways to ensure null safety. Java APIs and external libraries provide many techniques. However, there’s nothing shameful to fall back to simple if statements, as it’s clean, simple, and explicit.

The main goal of null checking is to do it as early as possible and ensure it’s uniform across the project. The way we’re doing it isn’t essential.

As usual, all the code from the tutorial is available over on GitHub.

       

Viewing all articles
Browse latest Browse all 4536

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>