// These would throw NPE if city is null:
city.equals(otherCity);
// Old school workaround:
if (city != null && city.equals(otherCity))
// Clean, null-safe:
Objects.equals(city, otherCity); // returns true if both are null, false if only one is
null should not equal null. Objects.equals is bad. SQL gets this better.
null mostly means what you want it to mean, but java itself inherently 'forces' it upon you when you create an array of a reference type (all cells of the array start out as null; inherent in the language, you can work around it with Arrays.fill), and any field that lacks an initializer (or is somehow accessed before that initializer has executed) is null.
But, mostly - it's what you want it to mean.
But here's thing - null is inflexible. It throws an exception no matter what question you ask a null object and you cannot change this.
Hence, there is one, and only one, meaning that null should ever have: The semantic meaning of "it doesn't exist at all - therefore it is silly to even begin to ask the question". If I ask a string how long it is, "" would respond with 0. nullshould not (and indeed, does not - it 'responds' with an NPE instead). That's correct. Because how long is an unknown string?
The answer is.. unknown. That's sort of the point. NPE is what you want here.
I have 2 strings. For whatever reason you cannot access them currently. For example because whatever service was meant to give them to me hasn't given them to me yet.
Are they equal?
Yes. No. Maybe? I don't know!
Objects.equals says that these 2 unknown concepts are equal. This is, at a fundamental level, wrong. Subtly so perhaps, but wrong.
What's really happening is that you're associating semantic meaning to null itself. This is a bad idea.
The same thing occurs anytime you see this code:
if (x == null || x.isEmpty()) ...
That code is usually a code smell. Because the code was never intended as an actual OR construct. Instead it is semantically confused about how x referring to some specific semantically well defined state (namely: Empty) is actually represented. Empty string? null? I don't remember, fuck it, let's just cover both bases.
This is a bad way to code. And it leads to unexpected NPEs that you then don't like and makes you say delirious things like 'null is a billion dollar invention' or whatever that was.
Objects.requireNonNullElse is not inherently 'wrong' here. That's just a way to convey the idea of: "I want to do an operation on an expression, where that expression is the notion: "If X is initialized, I want X, but if it is not, I want this default value" which is totally reasonable.
Objects.equals is not so lucky. It is semantically confused. "If X and Y are both present, I want to compare them. If one is present but the other is as yet uninitialized, I want to for some bizarre reason conclude that therefore X and Y must not be equal. Except if both are uninitialized; then they ARE equal." This entire concept is hopelessly confused about the difference between a reference itself and the object a reference is referencing.
The fact that you think Objects.equals is highly useful is why you hate null. Because you're using it wrong.
When you do it 'right', null rarely occurs. The classic "If your method returns a list and you want to return the notion that no results have been found, then return an empty list. Do not return null" is one rather trite example of how to 'do it right'.
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.
An optimization requires you to perform more work to save the computer work. If you perform more work to inflict more work on the computer, you are not optimizing but pessimizing.
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.
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.
Bonus in that the JIT basically makes it equivalent performance wise.
The only annoying thing about the method is that some null analysis tools do not like when you pass a nullable.. namely checker (you can change the stubs though). whoops I mean the non default fallback one.
The Objects.requireNonNull... methods are most commonly used in constructors to ensure that no null slips into a field. These fields are most often final and the one-liner works really well with that:
private final City city;
public SomeType(SomeForm form) {
this.city = Objects.requireNonNullElse(form.getCity(), defaultCity)
}
If a code base uses these methods with some frequency (mine do), I recommend to statically import them.
really at this point the Objects#requireNonNull family of functions are best for this example. Optional should be reserved mostly to do function chaining.
Here's the choices, basically, besides the ternary.
// needs to create Optional instance
var city = Optional.ofNullable(form.getCity()).orElse(defaultCity);
// no extra wrappers, the impl here is the ternary but re-uses the result from the single call
var city = Objects.requireNonNullOrElse(form.getCity(), defaultCity);
// still no wrappers, but 4 vs 1 line.
var city = switch (form.getCity()) {
case null -> defaultCity;
case City c -> c;
};
// trad with enhancements, avoids double-call, still 4 lines
City city = defaultCity;
if (form.getCity() instanceof City c) {
city = c;
}
// very traditional - and still very readable
City city = form.getCity();
if (city == null) {
city = defaultCity;
}
And then after some time it will become City city = defaultCity; Optional<City> optionalCity = getCity(); If (optionalCity != null & optionalCity.isPresent()) { city = optionalCity.get(); }
If you need to check if Optional<City> field is not null, you're kind of defeating the point of not having a default value for it. Just set it to Optional.empty() then only do a optionalCity.isPresent() check every time.
I started doing this when another senior colleague would always flag it in my PR and say “don’t let your objects get into an invalid state.”
Now I’m in a project where we’ve adopted this practice and the new engineering manager has come in and ordered us all to remove them claiming it adds to cognitive load. His reasoning is that we can look at all the call sites and confirm that as of now, none will produce nulls. And if in the future we call into something, the dev and the reviewers should know to check that no nulls happen in whatever spots (which sounds very error prone to me).
Ugh, if your senior is so confident that a thing will never be allowed to happen, the way you'd confirm this is not by having to look at call sites. Does this not increase cognitive load?
I would think this is what usage of @ NonNull with static analysis is for, now you don't need to distract yourself by checking any call sites.
I get the idea of reducing complexity by never allowing something to happen (so it never needs to be checked for), but if the method for avoiding the bad thing is 'everybody try really hard not to make the mistake', I feel that person learned some of the wrong lessons in their career. You don't avoid having bugs by trying really hard not to have bugs....
The way you phrased it, it sounds suicidal from the project's perspective. "the dev and the reviewers should know to check" is a bad idea. Maybe he meant that nulls should only be checked at the boundary (entry points), and then all the code that is the implementation doesn't need to check nulls again.
For example:
public int sumTrace(Matrix m1, Matrix m2) {
// require non-null check here
int trace1 = tr(m1);
int trace2 = tr(m1);
return trace1 + trace2;
}
private int tr(Matrix m) {
// no need to check null since the input was sanitized
// ...
}
Static imports can cause readability issues because it's not clear where the method comes from. There are some cases, like the Collectors class where it's not too ambiguous.
I personally think that Java is getting worse not better with each of these additions.
If != null is perfectly readable and clear :/ I find myself liking Go more and more each time I see these simplifications that are overly verbose for no reason… but maybe I’m just getting old…
Edit: Thank you everyone for commenting, I've enjoyed reading different perspectives and I really tried to clarify my thoughts and reply to everyone.
imo using Optional to dodge nullities like this is kind of abusing it. It's goated for streams and the like, not to dodge != null checks. In this specific example Optional.ofNullable(form.getCity()).orElse(defaultCity) can still result in an Optional of null (in case defaultCity is also null somehow). In which case you're still fucked. Unwrapping an Optional.ofNullable(null) does give you null and if you use that with the expectation of not having to deal with NPE you're gonna unwrap the Optional and get bodied.
(edit: and using Optional.of(form.getCity()).orElse(defaultCity) instantly throws an NPE and does not proceed to the orElse if form.getCity() is null.)
Meanwhile, Objects.requireNonNullElse(form.getCity(), defaultCity) will throw an NPE if both form.getCity() and defaultCity are null. Fails fast, fails where you'd expect something like this to fail. Very nice.
If it was in the language since day 1, everyone would be static importing def(nullable, defaultValue) and not debating about readability because "of course everyone knows the default value function"
You can debate about the readability to people outside the skill niche, or how accessible it is for newcomers, but Objects.requireBlahBlah is just too much visual noise for something so simple.
I agree, I think that verbosity has totally increased.
On top of the new functions being quite lengthy, I think that people chaining too many stream/optional functions makes it really hard to read code. Like 3-4 short chains is fine, but if it goes up to 10 it just becomes unreadable for me.
It’s not the type of code I like reading in general, might be preference based. I thought we peaked ~2015 w Java 8, everything after that has been downhill for me :/ except for virtual threads - those are epic.
Hmm so for example the function from the comment requireNonNullElse, I just googled it and it looks like it’s been added in 2017 Java 9, did it really need to be, if people wanted it couldn’t they have just included a library?
I feel like after Java 8 the release cadence has sped up drastically leading to a ton of standard library expansions/features being included into the language that should not have been included. There are way too many ways to get things done and I think that over time it will lead to code quality drops (due to devs misunderstanding the code/language features).
I’ll do another hot take: If Java keeps adding features at this pace it will eventually become another scala.
Got the hot take in now we wait for the dislikes haha
Part of what makes a language nice is not having to use a library for every little thing. Something as simply as using a default value should not have to be disconnected from the standard library. Yes, it's as easy as editing a config file or running a command, but it's still not connected to the regular user experience.
Languages evolve. The popular and default way to do somethings in 2008 SHOULD be different from how it's done in 2026 because if it's not, then that means absolutely no progress has been made throughout that time.
Saying something that makes no sense doesn't necessarily make it a hot take.
Interesting, we don’t disagree about languages evolving, I think well thought out features that simplify development are great. I just don’t think this is it, I think we’re adding a lot of bloat to the language. I could be wrong and the next 10-15 years will definitely prove it one way or the other.
The ‘hot take’ was a joke, but which parts of it do you find nonsensical? I was trying to make a parallel (and maybe poorly) between scala a crazy feature packed language in 2016 and it’s trajectory (downwards) and Javas future trajectory if it keeps adding things at this pace. But if you have genuine thoughts about this I’m all ears, like do you think it’s not changing too fast?
Yeah, the need to do one liners is the opposite of being clear, it creates more abstractions and leads to debugging being a bit of a hassle to deal with.
IMO the main advantage of optionals is for legacy code where you need to convey the possibility of a null value occurring from some weird-ass legacy function, because time constraints prevent you properly rooting into why, preventing that null and adding proper test coverage.
I said "family" for a reason. There are also HQ9++ which extends the language with object oriented concepts, and HQ9+- which adds exceptions. Very fascinating languages!
While I have your attention, did you ever come across the programming language Whitespace?
It's not so much the one liner aspect, but the single assignment aspect as a reason to do this. Using a multiline switch expression or ternary spread over multiple lines is also good (only a single assignment).
I don't really understand the need to make it into one line. You're adding more unneeded abstraction. If you decide later you need to add more checks if city is null, well you have to go back to the traditional way.
Readability wise, the bottom one is better. Performance wise, the bottom one is still faster (I know for this case the difference is negligible but point still stands). Code adaptability wise, the bottom is more flexible.
if you are debugging the behaviour of the JDK itself rather than just looking at what it returns, that feels like you don't really understand what you are trying to debug
I am by no means a FP connoisseur, but I do use a sprinkling and I think of the biggest values is that FP functions are supposed to be "pure" meaning the same inputs will yield the same outputs. These types of functions are easier to test and require less/no mocking. I've seen some people suggest a good application architecture is "functional core, imperative shell" (eg: https://testing.googleblog.com/2025/10/simplify-your-code-functional-core.html).
8
u/kubelke Feb 17 '26
What until you find out that you can use Objects.equals that supports null
63
u/zattebij Feb 17 '26
final City city = Optional.ofNullable(form.getCity()).orElse(defaultCity);... is still more readable imo, plus you can use
orElseGetto avoid getting the defaultCity when it's not required.39
u/Evening_Total7882 Feb 17 '26
Probably it’s because I’m used to requireNonNull, but this name always suggests an exception to me. firstNonNull(…,…)?
8
u/agentoutlier Feb 17 '26
Bonus in that the JIT basically makes it equivalent performance wise.
The only annoying thing about the method is that some null analysis tools do not like when you pass a nullable.. namely checker (you can change the stubs though).whoops I mean the non default fallback one.6
u/nicolaiparlog Feb 18 '26
The
Objects.requireNonNull...methods are most commonly used in constructors to ensure that nonullslips into a field. These fields are most often final and the one-liner works really well with that:If a code base uses these methods with some frequency (mine do), I recommend to statically import them.
13
u/yk313 Feb 17 '26
I’ll give you my ternary operator when you pry it from my cold, dead hands.
City city = from.getCity() != null ? from.getCity() : defaultCity;
7
u/nlisker Feb 17 '26
SO has a long discussion on this. But yes, it's a known API and I'm surprised when people don't know it.
1
u/BeyondFun4604 Feb 18 '26
Which java version were you using
14
u/narrow-adventure Feb 17 '26 edited Feb 18 '26
I personally think that Java is getting worse not better with each of these additions.
If != null is perfectly readable and clear :/ I find myself liking Go more and more each time I see these simplifications that are overly verbose for no reason… but maybe I’m just getting old…
Edit: Thank you everyone for commenting, I've enjoyed reading different perspectives and I really tried to clarify my thoughts and reply to everyone.
4
u/hiasmee Feb 17 '26
Suggestion: Why not do it where form is created?
2
u/strat-run Feb 20 '26
My how did I go so long without this feature was the Optional class. So many null pointer checks and exceptions could have been avoided.
2
u/witness_smile Feb 22 '26
You can even use Optionals and write
And you can even chain it, say the city is in a nested object like Form -> Address -> City
And when any part of the Optional chain is null, it will short circuit to the default value
3
u/brunocborges Feb 18 '26
A-há! It was already there! :D
https://javaevolved.github.io/errors/require-nonnull-else.html
1
u/BordicChernomyrdin Feb 18 '26
Same here! I just used this for the first time last week!
1
u/nekokattt Feb 18 '26
i like requireNonNullElseGet
1
u/red_dit_nou Feb 20 '26
Two words: Ternary Operator
0
u/White_C4 Feb 18 '26
I don't really understand the need to make it into one line. You're adding more unneeded abstraction. If you decide later you need to add more checks if city is null, well you have to go back to the traditional way.
Readability wise, the bottom one is better. Performance wise, the bottom one is still faster (I know for this case the difference is negligible but point still stands). Code adaptability wise, the bottom is more flexible.
-4
u/Gnerglor Feb 18 '26
Or you could just upgrade to Kotlin.
0
u/[deleted] Feb 18 '26
[deleted] — view deleted comment
1
u/[deleted] Feb 18 '26
[removed] — view removed comment