From 21395b444b963a23a3aca4d4e84e200d96b98d61 Mon Sep 17 00:00:00 2001 From: Mitya Lyubarskiy Date: Wed, 29 Jan 2020 03:08:15 -0800 Subject: [PATCH] [nullsafe] Documentation and reorder methods in `Assertions` Summary: Reorder assertNotNull and assumeNotNull: 1. More useful methods go first. 2. More useful methods explicitly recommended over less useful. Reviewed By: artempyanykh Differential Revision: D19599084 fbshipit-source-id: 1b9ad9ef6 --- .../facebook/infer/annotation/Assertions.java | 37 ++++++++++++++----- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/infer/annotations/src/main/java/com/facebook/infer/annotation/Assertions.java b/infer/annotations/src/main/java/com/facebook/infer/annotation/Assertions.java index 61b823a13..faf4ac728 100644 --- a/infer/annotations/src/main/java/com/facebook/infer/annotation/Assertions.java +++ b/infer/annotations/src/main/java/com/facebook/infer/annotation/Assertions.java @@ -13,14 +13,19 @@ import javax.annotation.Nullable; public class Assertions { - public static T assumeNotNull(@Nullable T object) { - return object; - } - - public static T assumeNotNull(@Nullable T object, String explanation) { + /** Assertion with a runtime check. */ + public static T assertNotNull(@Nullable T object, String explanation) { + if (object == null) { + throw new AssertionError(explanation); + } return object; } + /** + * See {@link #assertNotNull(T object, String explanation)}. + * + *

NOTE: prefer always providing an explanation. + */ public static T assertNotNull(@Nullable T object) { if (object == null) { throw new AssertionError(); @@ -28,10 +33,24 @@ public class Assertions { return object; } - public static T assertNotNull(@Nullable T object, String explanation) { - if (object == null) { - throw new AssertionError(explanation); - } + /** + * Same as {@link #assertNotNull()}, but does not do a runtime check. Useful in + * performance-critical places when a runtime check is costly. + * + *

NOTE: Whenever possible, prefer using {@link #assertNotNull()}. Java runtime is doing a good + * job with optimizing nullability checks, so most likely this won't improve performance, but will + * make unexpected null propagate and hide the real cause of an error. + */ + public static T assumeNotNull(@Nullable T object, String explanation) { + return object; + } + + /** + * See {@link #assumeNotNull(T object, String explanation)}. + * + *

NOTE: prefer always providing an explanation. + */ + public static T assumeNotNull(@Nullable T object) { return object; }