From 9cdfdca525423e2d34bd799e83c3fcdbb9570b91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Deleuze?= Date: Wed, 27 Mar 2024 15:35:35 +0100 Subject: [PATCH] Updated Code Style (markdown) --- Code-Style.md | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) 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