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)`](https://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#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.
A typical check for null in argument would be as follow:
We can use Java's
Objects#requireNonNull(T)helper method instead. It automatically throws aNullPointerExceptionfor us.For setters and constructors, we can also "inline" this check, by doing this:
Note that this is only allowed if it is a direct assignment, otherwise, never inline it.