Skip to content

UseNullable

Googler edited this page Aug 24, 2020 · 15 revisions

Use @Nullable

To eliminate NullPointerExceptions in your codebase, you must be disciplined about null references. We've been successful at this by following and enforcing a simple rule:

Every parameter is non-null unless explicitly specified.

The Guava: Google Core Libraries for Java and JSR-305 have simple APIs to get a nulls under control. Preconditions.checkNotNull can be used to fast-fail if a null reference is found, and @Nullable can be used to annotate a parameter that permits the null value:

import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Nullable;

public class Person {
  ...

  public Person(String firstName, String lastName, @Nullable Phone phone) {
    this.firstName = checkNotNull(firstName, "firstName");
    this.lastName = checkNotNull(lastName, "lastName");
    this.phone = phone;
  }

Guice forbids null by default

Guice will refuse to inject null and throw a ProvisionException with NULL_INJECTED_INTO_NON_NULLABLE error instead. If null is permissible by your class, you can annotate the field or parameter with @Nullable.

Note on null injected into @Provides method

Due to an oversight, Guice allowed null to be injected into @Provides methods in the past. When this oversight was fixed, an option to control the enforcement level was added to avoid breaking existing code:

  • IGNORE: null is allowed to be injected into @Provides methods
  • WARN: a warning is logged when null is injected into a @Provies method
  • ERROR: an error is thrown when when null is injected into a @Provides method

ERROR level enforcement is recommended so that:

  • Guice consistently rejects null unless @Nullable is used
  • NullPointerExceptions are caught early by Guice in all types of injections

Guice by default uses ERROR so you don't need to do anything to configure this. However, if for some reason that you need to relax this enforcement level, you can do so by setting the JVM property "-Dguice_check_nullable_provides_params" to either WARN or IGNORE.

Supported @Nullable annotations

Guice recognizes any @Nullable annotation that targets ElementType.PARAMETER (for parameters) or ElementType.FIELD (for fields), like edu.umd.cs.findbugs.annotations.Nullable or javax.annotation.Nullable.

Annotations like org.checkerframework.checker.nullness.qual.Nullable that target TYPE_USE and/or TYPE_PARAMETER will not work because those are not returned by the methods that Guice uses to get the annotations at runtime for the nullability checks. So make sure that you are importing the correct @Nullable when marking a parameter or a field as @Nullable in Guice.

Clone this wiki locally