diff --git a/Code-Style.md b/Code-Style.md index a768d27..3fd313a 100644 --- a/Code-Style.md +++ b/Code-Style.md @@ -287,9 +287,31 @@ public class MyClass { } ``` +[`org.springframework.lang.Contract` annotation](https://docs.spring.io/spring-framework/docs/6.2.0-SNAPSHOT/javadoc-api/org/springframework/lang/Contract.html) can be used to specify some aspects of the method behavior depending on the arguments that are then [taken in account by NullAway](https://github.com/uber/NullAway/wiki/Supported-Annotations#contracts). See for example how `@Contract` is used in Spring Framework codebase in the `Assert` class: +```java +public abstract class Assert { + // ... + @Contract("false, _ -> fail") + public static void state(boolean expression, String message) { + if (!expression) { + throw new IllegalStateException(message); + } + } + // ... + @Contract("null, _ -> fail") + public static void notNull(@Nullable Object object, String message) { + if (object == null) { + throw new IllegalArgumentException(message); + } + } + // ... +} +``` + +Those contract allows NullAway static analysis to understand that after an invocation of `Assert.state(value != null, "Value must not be null")` or `Assert.notNull(value, "Value must not be null")`, a nullable `value` can be considered as non nullable. + Related guidelines: - When overriding a method, null-safety annotations of the super method need to be specified on the overridden method unless you want to override null-safety. - - [`org.springframework.lang.Contract` annotation](https://docs.spring.io/spring-framework/docs/6.2.0-SNAPSHOT/javadoc-api/org/springframework/lang/Contract.html) can be used to specify some aspects of the method behavior depending on the arguments. - Use `@SuppressWarnings("NullAway")` when NullAway triggers irrelevant errors, which can happen due to [NullAway bugs or missing features](https://github.com/uber/NullAway/issues) or when the analysis is not able to prove null-safety (can happen with lambdas). ### Use of @Override