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

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

@yamgent

Description

@yamgent

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions