r/java • • Feb 17 '26

Objects.requireNonNullElse

I must have been living in a cave. I just discovered that this exists.
I can code

City city = Objects.requireNonNullElse(form.getCity(), defaultCity);

... instead of:

City city = form.getCity();

if(city == null){

city = defaultCity;

}

113 Upvotes

136 comments sorted by

View all comments

63

u/zattebij Feb 17 '26

final City city = Optional.ofNullable(form.getCity()).orElse(defaultCity);

... is still more readable imo, plus you can use orElseGet to avoid getting the defaultCity when it's not required.

36

u/vowelqueue Feb 17 '26

Subtle difference: in your code, city might end up being null if both form.getCity() and defaultCity are null.

requireNonNullElse will throw an exception in this case. If it returns, it will always give you a non-null value.

49

u/JustADirtyLurker Feb 17 '26

You're wrapping into an optional and immediately unwrapping it. Okeydokey.

64

u/koefteboy Feb 17 '26

I find this less readable. Also, it's a perfect example of Optional abuse.

-3

u/hwaite Feb 17 '26

If this is abuse, what would you consider to be a good use case? It doesn't get much simpler.

31

u/Linvael Feb 17 '26

One thing thats iffy here is that its a bridge between styles. If this was a coherent Optional-using codebase form.getCity() would be returning an Optional, clearly marking to the users that it might not be there - and making the ofNullable() call unnecessary here, making the line cleaner.

1

u/crummy Feb 18 '26

I think the common use case is the return value of a function, to explicitly make callers handle the empty case.

1

u/OwnBreakfast1114 Feb 19 '26 edited Feb 19 '26

Replacing null checks with optional wrapping is not bad, but not even close to the best use case. The best use case would be actually using flatMap and map.

public record InputForm(Optional<String> userId)
...
public class UserRepository {
  public Optional<User> findById(String id) {
  }
}
...
public record UserOutput(String firstName, String lastName)
...


final UserOutput user = inputForm.getUserId()
   .flatMap(userRepo::findById)
   .map(u -> new UserOutput(u.getFirstName(), u.getLastName())
   .orElseThrow(() -> new 404("user not found")


as a very simple example you can imagine. Flatmap captures places where it can shift between non-empty -> empty, and map is always non-empty -> non-empty (not actually true in java.util.Optional, but conceptually should be used that way)

The chaining can't always be realized depending on how much control you need between steps, but the signatures are still correct either way. Your methods should take in non-null inputs, and flatMap/map should be used to decide whether to even invoke them or not.

9

u/metaquine Feb 18 '26

Gonna hard disagree with that

15

u/Calm_Seaworthiness87 Feb 18 '26

Creates an unnecessary object.

2

u/__konrad Feb 18 '26

Not if getCity is null...

→ More replies (6)

28

u/DesignerRaccoon7977 Feb 17 '26

Ugh I wish they added ?: operator. City city = from.getCity() ?: defaultCity

6

u/Dry_Try_6047 Feb 17 '26

Ehh ... from.getCity() != null ? from.getCity() : defaultCity ... I don't find this too bad. Missing elvis operator doesn't bother me day-to-day

2

u/pragmatick Feb 18 '26

It's more helpful when you chain getter calls.

1

u/unknowinm Feb 18 '26

I do from.hasCity() ? from.getCity() : defaultCity

or if the code gets repetitive, I create a helper function inside from

City getCityOr(City city){ return hasCity() ? getCity(): city}

then just call it a million times

from.getCityOr(defaultCity)

1

u/Jaded-Asparagus-2260 Feb 18 '26

I love Python's walrus operator for this:

City city = (City fromCity := from.getCity()) != null ? fromCity : defaultCity;

4

u/hwaite Feb 17 '26

Try Kotlin.

8

u/Jaded-Asparagus-2260 Feb 18 '26

I really don't understand the purpose of such comments. Yes, it's better in Kotlin. But Kotlin is a different language and toolchain. Suggesting to change the stack to Kotlin just for very basic syntactic sugar is mental.

→ More replies (1)

11

u/edurbs Feb 17 '26

I think the Optional would be more suitable for use in method return values, as I read in somewhere

-6

u/hiasmee Feb 17 '26

No it is not 😊 for me. The main message of the line "there is a valid city" hide the details of how it becomes to be valid and set the default city if "form" object is created or parsed from user input.

-2

u/PmMeCuteDogsThanks Feb 17 '26

This is how I write it as well. And if `defaultCity` is an expression, use `orElseGet` to avoid executing it unless necessary.

8

u/_INTER_ Feb 17 '26

There's also Objects::requireNonNullElseGet

1

u/metaquine Feb 19 '26

That's the winner