Revise use of Objects.requireNonNull()

Historically, we have rarely intentionally thrown a
NullPointerException in the Spring Framework. Instead, we prefer to
throw either an IllegalArgumentException or IllegalStateException
instead of a NullPointerException.

However, changes to the code in recent times have introduced the use of
Objects.requireNonNull(Object) which throws a NullPointerException
without an explicit error message.

The latter ends up providing less context than a NullPointerException
thrown by the JVM (since Java 14) due to actually de-referencing a
null-pointer. See https://openjdk.org/jeps/358.

In light of that, this commit revises our current use of
Objects.requireNonNull(Object) by removing it or replacing it with
Assert.notNull().

However, we still use Objects.requireNonNull(T, String) in a few places
where we are required to throw a NullPointerException in order to
comply with a third-party contract such as Reactive Streams.

Closes gh-32430
This commit is contained in:
Sam Brannen
2024-03-13 14:31:33 +01:00
parent d6422d368a
commit 986c4fd926
11 changed files with 37 additions and 27 deletions

View File

@@ -17,7 +17,6 @@
package org.springframework.test.web.reactive.server;
import java.time.Duration;
import java.util.Objects;
import java.util.function.Consumer;
import org.hamcrest.Matcher;
@@ -213,10 +212,13 @@ public class CookieAssertions {
private ResponseCookie getCookie(String name) {
ResponseCookie cookie = this.exchangeResult.getResponseCookies().getFirst(name);
if (cookie == null) {
if (cookie != null) {
return cookie;
}
else {
this.exchangeResult.assertWithDiagnostics(() -> fail("No cookie with name '" + name + "'"));
}
return Objects.requireNonNull(cookie);
throw new IllegalStateException("This code path should not be reachable");
}
private static String getMessage(String cookie) {

View File

@@ -19,7 +19,6 @@ package org.springframework.test.web.reactive.server;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import org.hamcrest.Matcher;
@@ -200,10 +199,13 @@ public class HeaderAssertions {
private List<String> getRequiredValues(String name) {
List<String> values = getHeaders().get(name);
if (CollectionUtils.isEmpty(values)) {
if (!CollectionUtils.isEmpty(values)) {
return values;
}
else {
this.exchangeResult.assertWithDiagnostics(() -> fail(getMessage(name) + " not found"));
}
return Objects.requireNonNull(values);
throw new IllegalStateException("This code path should not be reachable");
}
/**