Not null arguments in Java public methods

As Java programmer, one of my references is Joshua Bloch’s Effective Java. In this book, the theme 38 says we should always check the validity of the arguments on each method.

No excuse.

For example, let’s have a very dummy method which prints on the standard output the length of the String passed as argument:

public void metSimple(String arg) {
    System.out.println(arg.length());
}

if we call this method with a null String, we will get a Null Pointer Exception (NPE) at run-time.

Accordingly to Bloch’s book, we should add a proper check to validate the argument like as follow:

public void metChecked(final String arg) {
    if (arg == null) {
        throw new NullPointerException("Argument arg is null");
    }
    System.out.println(arg.length());
}

The check will assure us that the body of the method (here just a simple System.out.println but in real code will be more complex) can work on the argument arg without problems, knowing that the string arg is not null.

Note: we should not use assert instructions to check public methods arguments. Reason is that assert can be disabled. There is also an old but still valid Java article on assertions on this.

The nullity check is done at run-time so we need to work on testing side to have reasonable confidence that null condition (i.e the NPE) will not really happen in front of our customers.

Can we also have some support during coding? I mean, from our fabulous IDE?

Yes, but we need to help them, adding a “not null” annotation on the argument. There are several of these annotations but the standard is @javax.annotation.Nonnull.

Our method becomes:

public void metAnnotatedChecked(@Nonnull final String arg) {
    if (arg == null) {
        throw new NullPointerException("Argument arg is null");
    }
    System.out.println(arg.length());
}

The @Nonnull annotation is from jsr305 library. Maven users can add it in the pom the following dependency:

<dependency>
    <groupId>com.google.code.findbugs</groupId>
    <artifactId>jsr305</artifactId>;
    <version>2.0.1</version>;
</dependency>

The @Nonnull annotation simply says: dear method users, do not try to invoke it with a null as argument.

Important: the @Nonnull annotation is simply an annotation, a kind of hint for the tools. It is not a run-time check and it does not enforce or guarantee that nobody can call the method with a null argument. So our “if arg == null” check should stay there.

The IDEs use these annotations (there are also others like CheckForNull) to perform additional checks (named “null analysis”) during coding. Not at run-time. These checks complements the run-time checks.

Let’s how most popular IDEs use these annotations. To check their behavior I created a calling class as follows: