Skip to content

Introduce @Contract annotation for nullability constraints #4722

@sbrannen

Description

@sbrannen

Overview

We recently introduced support for JSpecify nullability annotations; however, there are many use cases where additional nullability constraints would prove very beneficial.

Here is a concrete example.

@SuppressWarnings("NullAway") // StringUtils.isBlank() does not yet have a nullability @Contract
public static ConditionEvaluationResult disabled(@Nullable String reason, @Nullable String customReason) {
if (StringUtils.isBlank(reason)) {
return disabled(customReason);
}
if (StringUtils.isBlank(customReason)) {
return disabled(reason);
}
return disabled("%s ==> %s".formatted(reason.strip(), customReason.strip()));
}

To address issues such as the one above, we should introduce a @Contract annotation analogous to the one in the Spring Framework.

By annotating StringUtils.isBlank() as follows, we would then be able to remove the @SuppressWarnings("NullAway") declaration on ConditionEvaluationResult.disabled(String, String), since NullAway would infer that a null reason or customReason would always result in early termination of the method, thereby avoiding a possible NullPointerException when strip() is invoked on those parameters.

@Contract("null -> true")
public static boolean isBlank(@Nullable String str) {
	return (str == null || str.isBlank());
}

Deliverables

  • Introduce @Contract annotation in junit-platform-commons (package to be determined).
  • Apply @Contract annotations throughout the codebase, where applicable, but especially on public APIs for extensions, assertions, assumptions, etc.

Related Issues and Resources

Metadata

Metadata

Assignees

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions