rewrite-migrate-java icon indicating copy to clipboard operation
rewrite-migrate-java copied to clipboard

Replace Optional.get with Optional::orElseThrow

Open yeikel opened this issue 3 years ago • 3 comments

Java 10 recommends orElseThrow instead of get:

https://docs.oracle.com/javase/10/docs/api/java/util/Optional.html#get()

Some background:

http://mail.openjdk.java.net/pipermail/core-libs-dev/2016-April/040531.html


val value = Optional.of("").get();

val value = Optional.of("").orElseThrow(NoSuchElementException::new);

yeikel avatar Nov 14 '22 20:11 yeikel

Might fit better in rewrite-migrate-java, due to the minimum Java version.

timtebeek avatar Nov 14 '22 20:11 timtebeek

Might fit better in rewrite-migrate-java, due to the minimum Java version.

Both methods were introduced in Java 8 but the recommendation started in Java 10 after long discussions on the Java user list. I wouldn't consider this a requirement on a specific version though

Using this pattern in Java 8 is not flagged at the Java docs but it is still dangerous and a bad practice

To me, this recipe can and should also be applied in Java 8 codebases

yeikel avatar Nov 15 '22 03:11 yeikel

I would add that in 10+ simplify to orElseThrow()?

jkschneider avatar Dec 29 '22 20:12 jkschneider