What’s the point of Guava checkNotNull [duplicate]

The idea is to fail fast. For instance, consider this silly class:

public class Foo {
    private final String s;

    public Foo(String s) {
        this.s = s;
    }

    public int getStringLength() {
        return s.length();
    }
}

Let’s say you don’t want to allow null values for s. (or else getStringLength will throw a NPE). With the class as-is, by the time you catch that null, it’s too late — it’s very hard to find out who put it there. The culprit could well be in a totally different class, and that Foo instance could have been constructed a long time ago. Now you have to comb over your code base to find out who could possibly have put a null value there.

Instead, imagine this constructor:

public Foo(String s) {
    this.s = checkNotNull(s);
}

Now, if someone puts a null in there, you’ll find out right away — and you’ll have the stack trace pointing you exactly to the call that went wrong.


Another time this can be useful is if you want to check the arguments before you take actions that can modify state. For instance, consider this class that computes the average of all string lengths it gets:

public class StringLengthAverager {
    private int stringsSeen;
    private int totalLengthSeen;

    public void accept(String s) {
        stringsSeen++;
        totalLengthSeen += s.length();
    }

    public double getAverageLength() {
        return ((double)totalLengthSeen) / stringsSeen;
    }
}

Calling accept(null) will cause an NPE to get thrown — but not before stringsSeen has been incremented. This may not be what you want; as a user of the class, I may expect that if it doesn’t accept nulls, then its state should be unchanged if you pass a null (in other words: the call should fail, but it shouldn’t invalidate the object). Obviously, in this example you could also fix it by getting s.length() before incrementing stringsSeen, but you can see how for a longer and more involved method, it might be useful to first check that all of your arguments are valid, and only then modify state:

    public void accept(String s) {
        checkNotNull(s); // that is, s != null is a precondition of the method

        stringsSeen++;
        totalLengthSeen += s.length();
    }

Leave a Comment