← All recipes
Moderne licensed

Relax Optional.of to Optional.ofNullable on nullable values

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

Rewrites Optional.of(x) to Optional.ofNullable(x) where the argument x is provably @Nullable at the call site. Optional.of(null) throws NullPointerException, while Optional.ofNullable(null) yields Optional.empty(), so the two factories diverge on the null path: this rewrite **changes observable runtime behavior** (an NPE becomes an empty optional) and therefore marks every call it changes for human review. The call is matched on java.util.Optional of(..); the argument's nullness is resolved from the nullness oracle and the path-sensitive flow engine (no name-based heuristics), so a value already null-checked on the path is not flagged. A non-null literal argument, or one already protected by a non-null assertion (requireNonNull / castToNonNull / …), is left untouched, keeping the recipe idempotent. Gated on the call site being in an annotated scope; 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.RelaxOptionalOfToOfNullable

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