Skip to content
This repository has been archived by the owner on May 28, 2022. It is now read-only.

Java: use Objects#requireNonNull() for argument validation #89

Open
yamgent opened this issue May 19, 2017 · 1 comment
Open

Java: use Objects#requireNonNull() for argument validation #89

yamgent opened this issue May 19, 2017 · 1 comment

Comments

@yamgent
Copy link
Contributor

yamgent commented May 19, 2017

A typical check for null in argument would be as follow:

void doSomething(Bar bar) {
    if (bar == null) {
        throw new NullPointerException();
    }
    bar.doMoreThings();
    ...
}

We can use Java's Objects#requireNonNull(T) helper method instead. It automatically throws a NullPointerException for us.

void doSomething(Bar bar) {
    requireNonNull(bar);
    bar.doMoreThings();
    ...
}

For setters and constructors, we can also "inline" this check, by doing this:

public Foo(Bar bar) {
    this.bar = Objects.requireNonNull(bar);
}

Note that this is only allowed if it is a direct assignment, otherwise, never inline it.

@yamgent yamgent changed the title Java: Use Objects#requireNonNull() for argument validation Java: use Objects#requireNonNull() for argument validation May 19, 2017
@yamgent
Copy link
Contributor Author

yamgent commented May 19, 2017

Google's Guava library also has more helper methods for different kinds of argument validation, although that means we will have a new dependency, so projects should probably write their own version of the helper methods:

https://github.com/google/guava/wiki/PreconditionsExplained

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant