Skip to content

Commit

Permalink
Prefer Optional#orElseGet over Optional#orElse for non-compile-time i…
Browse files Browse the repository at this point in the history
…nput
  • Loading branch information
mlrprananta committed Mar 10, 2023
1 parent c3cd535 commit cb0d519
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;

import com.google.common.collect.Streams;
import com.google.errorprone.matchers.CompileTimeConstantExpressionMatcher;
import com.google.errorprone.refaster.Refaster;
import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;
import com.google.errorprone.refaster.annotation.MayOptionallyUse;
import com.google.errorprone.refaster.annotation.NotMatches;
import com.google.errorprone.refaster.annotation.Placeholder;
import com.google.errorprone.refaster.annotation.UseImportPolicy;
import java.util.Comparator;
Expand Down Expand Up @@ -220,6 +222,22 @@ T after(Optional<T> o1, Optional<T> o2) {
}
}

/**
* Prefer {@link Optional#orElseGet(Supplier)} over {@link Optional#orElse(Object)} if the given
* value is not a compile-time constant.
*/
abstract static class OrElseToOrElseGet<T> {
@BeforeTemplate
T before(Optional<T> o, @NotMatches(CompileTimeConstantExpressionMatcher.class) T value) {
return o.orElse(value);
}

@AfterTemplate
T after(Optional<T> o, T value) {
return o.orElseGet(() -> value);
}
}

/**
* Flatten a stream of {@link Optional}s using {@link Optional#stream()}, rather than using one of
* the more verbose alternatives.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,4 +119,8 @@ ImmutableSet<Optional<String>> testOptionalFilter() {
Optional<String> testOptionalMap() {
return Optional.of(1).stream().map(String::valueOf).findAny();
}

ImmutableSet<String> testOrElseToOrElseGet() {
return ImmutableSet.of(Optional.of("foo").orElse("bar"), Optional.of("foo").orElse(toString()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,9 @@ ImmutableSet<Optional<String>> testOptionalFilter() {
Optional<String> testOptionalMap() {
return Optional.of(1).map(String::valueOf);
}

ImmutableSet<String> testOrElseToOrElseGet() {
return ImmutableSet.of(
Optional.of("foo").orElse("bar"), Optional.of("foo").orElseGet(() -> toString()));
}
}

0 comments on commit cb0d519

Please sign in to comment.