openrewrite / openrewrite/rewrite-migrate-java
Replace usage of Optional.isPresent => get => else with map-> orElseGet
Nobody has claimed this yet.
- 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:
- Check if the value of the optional is present
- If present, return it (or apply some transformation)
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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