← All recipes
Moderne licensed

Route a guarded raw accessor through its present Optional

Recipe IDio.moderne.nullability.CollapseOptionalPresentGuardToGet
Artifactio.moderne.recipe:rewrite-nullability

Inside the then-branch of an if (xOpt().isPresent()) { ... } guard, rewrites a sibling raw nullable accessor getX() to xOpt().get(), so the checker flows non-null through the Optional instead of needing a requireNonNull. NullAway flags the bare getX() dereference because the accessor is @Nullable, but the enclosing isPresent() guard already proves the corresponding Optional is present; reading through xOpt().get() re-expresses the same value via the guarded, provably-present Optional. The rewrite is gated for correctness over coverage: the guard must be exactly <recv>.isPresent() on a no-argument, side-effect-free Optional accessor; the rewritten getX() must be the matching no-argument raw accessor (same enclosing receiver, and <recv> named getX plus an Optional suffix) that is provably @Nullable here; and the use must be lexically inside the then-block so the guard dominates it. Because the Optional is proven present in the guarded branch, .get() cannot throw where the raw accessor did not, so runtime behavior is unchanged. Idempotent and conservative; only Java sources are modified.

Single recipeProprietary

Usage

This recipe has no required configuration options. You’ll need the Moderne CLI configured before running the command below.

mod run . --recipe io.moderne.nullability.CollapseOptionalPresentGuardToGet

If the recipe isn’t available locally, install it with:

mod config recipes jar install io.moderne.recipe:rewrite-nullability:0.3.1

Options

NameTypeDescription
annotatedPackagesStringComma-separated package prefixes to limit the fix to (matching NullAway's AnnotatedPackages option). When unset, the recipe fixes all packages.
e.g. com.example

Data tables

Structured output this recipe can produce.

  • Null-safety fixes by rungEach residual null-safety fix applied, tagged with the precedence rung that produced it, so the share bottoming out at a last-resort `requireNonNull` assertion can be tracked.io.moderne.nullability.table.NullFixes
  • Declined null-safety fixes needing reviewEach site the recipe declined to auto-fix because the fix is a design decision (the value is explicitly `null` on some path, so the slot likely should be `@Nullable`), for human triage.io.moderne.nullability.table.DeclinedNullFixes
  • Source files that had resultsSource files that were modified by the recipe run.org.openrewrite.table.SourcesFileResults
  • Source files that had search resultsSearch results that were found during the recipe run.org.openrewrite.table.SearchResults
  • Source files that errored on a recipeThe details of all errors produced by a recipe run.org.openrewrite.table.SourcesFileErrors
  • Recipe performanceStatistics used in analyzing the performance of recipes.org.openrewrite.table.RecipeRunStats