this post was submitted on 16 Jun 2023
14 points (100.0% liked)

Java

20 readers
1 users here now

For discussing Java, the JVM, languages that run on the JVM, and other related technologies.

founded 1 year ago
MODERATORS
 

I'm curious if there are things in the standard class library that you find useful but not widely used.

you are viewing a single comment's thread
view the rest of the comments
[–] pohart@lemmyrs.org 6 points 1 year ago (2 children)

Optional! I was reluctant at first because of the nullibility, but it's so useful.

I'm not sure this is what you were going for. I think most people know about optional and are skeptical because it's not a fix for nullability.

[–] BitPirate@feddit.de 3 points 1 year ago (1 children)

Don't forget its subtypes. OptionalInt, OptionalDouble etc. This avoids auto(un)boxing.

[–] pohart@lemmyrs.org 1 points 1 year ago

Oh wow that's great. I didn't know about those at all.

[–] JackbyDev@programming.dev 2 points 1 year ago (1 children)

I didn't have a specific goal, but yeah I do wish more people used Optional.

My one "gripe" with Optional (and I use it lightly) is that they mean for it to only be used as a return type instead of anywhere something can be optional. It can still be used as that though, they just don't recommend it.

[–] pohart@lemmyrs.org 1 points 1 year ago (1 children)

IMHO it should be used for parameters, as long as there is more than one optional parameter. If rather all non nullable parameters though, which is usually doable.

[–] JackbyDev@programming.dev 2 points 1 year ago (1 children)

I've waffled on it. Currently my opinion is to use whatever nullable annotation the project uses (if any, otherwise JetBrains's). Essentially, I'm not sure if the official recommendation to avoid Optional for uses other than return types has reasoning I'm missing.

I do use it like this though and lament that we don't have an Elvis operator (?:)

Optional.ofNullable(thingThatMightBeNull).map(e -> e.someMethod()).orElse(null);
[–] presumably_wrong@lemm.ee 0 points 1 year ago (1 children)

Instead of wrapping it in an optional you can do Objects.requireNonNullElse(value, defaultValue)

[–] austin@programming.dev 1 points 1 year ago* (last edited 1 year ago)

Optional has more syntactic sugar for more complex scenarios / functional call chaining that prevents repetitive if checks

Optional.ofNullable(myObj)
  .map(MyClass::getProperty)
  .map(MyOtherClass::getAnotherProperty)
  .filter(obj -> somePredicate(obj))
  .orElse(null)

This is completely null safe, the function calls are only made if the object is not null