From cbba01c9ba1be88e70ac6a9f366f7b77c2585be0 Mon Sep 17 00:00:00 2001 From: Phil Werli Date: Mon, 29 Apr 2024 10:00:11 +0200 Subject: [PATCH] Introduce `OptionalEmpty` Refaster rule --- .../errorprone/refasterrules/OptionalRules.java | 13 +++++++++++++ .../refasterrules/OptionalRulesTestInput.java | 4 ++++ .../refasterrules/OptionalRulesTestOutput.java | 4 ++++ 3 files changed, 21 insertions(+) diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/refasterrules/OptionalRules.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/refasterrules/OptionalRules.java index cf1c2cb3ce6..9f73ae38e6f 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/refasterrules/OptionalRules.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/refasterrules/OptionalRules.java @@ -27,6 +27,19 @@ final class OptionalRules { private OptionalRules() {} + /** Prefer {@link Optional#empty()} over the more contrived alternative. */ + static final class OptionalEmpty { + @BeforeTemplate + Optional before() { + return Optional.ofNullable(null); + } + + @AfterTemplate + Optional after() { + return Optional.empty(); + } + } + static final class OptionalOfNullable { // XXX: Refaster should be smart enough to also rewrite occurrences in which there are // parentheses around the null check, but that's currently not the case. Try to fix that. diff --git a/error-prone-contrib/src/test/resources/tech/picnic/errorprone/refasterrules/OptionalRulesTestInput.java b/error-prone-contrib/src/test/resources/tech/picnic/errorprone/refasterrules/OptionalRulesTestInput.java index ccd2d3f5b21..73f0a9be9c4 100644 --- a/error-prone-contrib/src/test/resources/tech/picnic/errorprone/refasterrules/OptionalRulesTestInput.java +++ b/error-prone-contrib/src/test/resources/tech/picnic/errorprone/refasterrules/OptionalRulesTestInput.java @@ -13,6 +13,10 @@ public ImmutableSet elidedTypesAndStaticImports() { return ImmutableSet.of(Streams.class); } + Optional testOptionalEmpty() { + return Optional.ofNullable(null); + } + ImmutableSet> testOptionalOfNullable() { return ImmutableSet.of( toString() == null ? Optional.empty() : Optional.of(toString()), diff --git a/error-prone-contrib/src/test/resources/tech/picnic/errorprone/refasterrules/OptionalRulesTestOutput.java b/error-prone-contrib/src/test/resources/tech/picnic/errorprone/refasterrules/OptionalRulesTestOutput.java index 2a2985fe9b5..bc8f38c0cd6 100644 --- a/error-prone-contrib/src/test/resources/tech/picnic/errorprone/refasterrules/OptionalRulesTestOutput.java +++ b/error-prone-contrib/src/test/resources/tech/picnic/errorprone/refasterrules/OptionalRulesTestOutput.java @@ -15,6 +15,10 @@ public ImmutableSet elidedTypesAndStaticImports() { return ImmutableSet.of(Streams.class); } + Optional testOptionalEmpty() { + return Optional.empty(); + } + ImmutableSet> testOptionalOfNullable() { return ImmutableSet.of(Optional.ofNullable(toString()), Optional.ofNullable(toString())); }