openrewrite / openrewrite/rewrite-migrate-java

Replace usage of Optional.isPresent => get => else with map-> orElseGet

Open
#1,048 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

recipe
Dominant language
Java
Stars
156
Forks
130
Avg merge
20h 57m
Merged PRs (30d)
21

Description

I am not sure how to word this recipe or if a recipe is appropriate here, but this is a common misuse of the Optional type

  • This is related to openrewrite/rewrite-static-analysis#56 but it is not quite the same

The pattern is usually:

  1. Check if the value of the optional is present
  2. If present, return it (or apply some transformation)
  3. Else, return a default

This is effectively the same as checking if something is null and returning a default value if that's the case.

This pattern can be replaced with map followed by orElseGet


--- a/src/Util.java
+++ b/src/Util.java
@@ -40,11 +40,7 @@ public class Util {
      */
     public static Json loadFrom(final String filePath) throws IOException {
         final Optional<String> jsonContent = loadJson(filePath);
-        if(jsonContent.isPresent()) {
-            return new Json(jsonContent.get());
-        } else{
-            return new Json();
-        }
+        return jsonContent.map(Json::new).orElseGet(Json::new);
     }


Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the Java recipe area responsible for Optional usage patterns and compare this request with openrewrite/rewrite-static-analysis#56. Define the supported isPresent/get/else shapes and verify that they can be expressed with map followed by orElseGet, including the transformation shown in the issue.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
tooling
Issue type
Refactor
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.