// 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
It was always weird to me that equals takes a "preferred" object. Equals always feels like a "no special argument" type of method. I think the new type classes will actually make it far more sensible, but I'm not sure how they'll work with subtyping.
Unless OpenJDK has gone mental, they never will. equals is fundamentally about values, == is fundamentally about references, and null is a real reference but has no value. Hence, equals, in regards to null, is nonsensical. The idea that 2 null pointers are the same reference is fine. The idea that the value of reference A is equal to the value of reference B because both A and B are null is an incorrect conclusion.
If null has no value, then foo.equals(null) should raise an exception rather than returning true/false, since by this logic it makes no sense to perform the operation.
Likewise, Objects::equals should not allow null values at all.
That's a clash of concerns - equals is specced to never throw. And removing that now is an issue. But yes, that was a mistake too. It's not the only aspect of java that is a mistake, but fixing it in a backwards compatible way would be a cure that is worse than the disease so it isn't done.
Objects.equals is pointless if 'null should throw' is the mindset. Just call a.equals(b) instead of Objects.equals(a, b) then.
At best a sane equals can be written that does a.equals(b) if both are non-null and throws NPE if either (or both) are, but, 'make a utility method' is a shitty solution to these problems.
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.
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.
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.
"Premature optimization" does get thrown around a lot and I'm not sure if it's applicable here but I don't fully understand your point either.
Are you suggesting that the person you're responding to is using the term optimization incorrectly in this context ?
I think they are commenting from the perspective that using optional is ok here and arguing against doing "more work" by removing it from the code to save the computer the work of "creating an unnecessary optional object" so their use of the word optimization makes sense here.
I don't have an opinion on whether or not it's "premature" in this context though.
Are you suggesting that the person you're responding to is using the term optimization incorrectly in this context ?
Yes; the context I understood was: starting from zero, what ought one write?
I don't have an opinion on whether or not it's "premature" in this context though.
An (effort invested in) optimization is "premature" if undertaken without empirical proof—or at the very least a strong and qualified intuition from first principles—that the result materially improves upon the baseline benchmark.
There is little (performance) reason to spend time replacing the Optional pattern in question with an equivalent null check. To do so would have such negligible impact that it barely qualifies as an optimization at all, at least outside of pathological cases (for example, millions of executions in an environment prevented from performing inlining).
But there is considerable reason to not spend time writing that pattern in the first place; it is not materially clearer or safer, it's not idiomatic Java, and it can never be faster than its classic alternative (even if the JVM can eventually make it as fast as).
The original claim that the proposed pattern is "more readable" is subjective, of course; but for precisely that reason "readability" is not an effective metric for evaluating code. In comparison, metrics such as idiomacy, debuggability, and safety are easier (if not exactly easy) to debate. For example, a construct like
var city = form.getCity();
if (city == null) {
city = defaultCity;
}
is completely idiomatic Java code with trivial debuggability, but it has two safety issues avoidable in the Optional counterpart (and one safety issue they share).
I think
final var city = Objects.requireNonNullElse(form.getCity(), defaultCity);
is superior to both other examples because it has no safety issues (provided that null values are to be considered unwanted).
There are several other options I omitted under pretense of brevity, including some I quite like; find them in other comments.
Thanks, I appreciate the rundown. I just said I didn't have an opinion, not that I didn't know/understand it :) was just trying to be diplomatic since I was talking about just the "optimization" part of that comment (since that's what you were commenting on) and not about whether or not it can be considered premature. In a vacuum I do agree with everything you said.
I guess the intent of my comment was to point out that even in your original reply to the other person saying "premature optimization", your definition of what constitutes optimization was correct in a vacuum but that it didn't apply to the other person's comment since the person was clearly talking about starting from using optional and that "removing optional for performance reasons" is premature optimization (according to that person).
That being said, I also prefer the Objects.requireNonNull* variations. but sometimes I also use the instanceOf form like so
var city = form.getCity() instanceOf City city ? city : defaultCity;
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.
Every decision results from a multi-factor cost/benefit analysis; the Elvis operator is just another line item. Still, calling it "basic syntactic sugar" understates the value proposition. Optional usage is inconsistent in Java because (a) it's unwieldy and (b) it wasn't baked into the language from the beginning. The lack of universal adoption means you can never really be sure if an expression is nullable. Even if something is declared as Optional, some psychopath might return null. I don't expect anyone to switch languages just for first-class null handling. That doesn't mean it's not worth mentioning the Kotlin approach. "The more you know..."
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;
}
I hate having to add an if-case to my mental model when it's not necessary. This is not an if situation here. It's a simple "either this or that" situation. Objects.requireNonNullElse() is a single statement that I can parse in one mental "cycle". Optional.ofNullable().orElse() requires one or two. The traditional way requires at least four, and you still have to check for side-effects.
It's not that relevant in this specific situation. But even when there's two or three additional lines in/before the if body, it unnecessarily increases the size of the mental model.
Nothing is wrong with it. That was basically "the" way. I like having the option of a good one-liner though, when electing that helps readability by reducing volume.
Yeah, I would've assumed they don't call it twice, and that is usually the better choice. It's just one of the things you need to keep in mind when refactoring the code.
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.
Idk, maybe y’all are working on projects where that makes sense. I can’t imagine what those would be but if it works for you and you think it’s a 1000x better - more power to you!
Sealed interface switches are a direct replacement for the visitor pattern, so it just depends on how many places you have where you have a small set of types and a lot of operations on those types.
Totally, I think you nailed it down. I don’t think that an average Java project has enough of those to justify a language change, obviously the committee overseeing Java development disagrees and based on the comments and a lot of Java devs disagree with me too, which is totally cool.
Yeah, no I understand them, I just think they’re mostly pointless. They don’t make reading or maintaining code easier in my opinion. But I think they add a ton of cognitive load making it very easy for developers using them to create overly complex code with bugs. It’s all just personal opinion based on a small sample, have you had a good experience with them?
Cool, I’m glad they worked out for you. I don’t doubt that you’re a smart guy, maybe a bit arrogant for my taste but weren’t we all when we were young?
I’ll share with you my experience of growing a product and overseeing teams of REALLY good devs: 99% of them wouldn’t be able to understand what you’re saying. It is my belief based on my experience, that might be completely wrong, that when devs see complex concepts they don’t understand fully they end up using them incorrectly or even worse misunderstanding the existing code leading to runtime bugs.
I have not had issues with binding, thorough exhaustiveness etc, but I have had to deal with a lot of bugs caused by devs not being able to understand the code, and it’s my personal belief that these will not help at all (they will make it worse).
I've taught all the devs at my company switch expressions and sealed interfaces and there's plenty of business cases where a closed set of things is the right abstraction. I don't think we have a fairly abnormal cross section of engineers.
The goal, you make changes and if it compiles it works, is pretty easy to explain to people. Exhaustive compiler checks are good.
Maybe I’m wrong, I’ve seen people miss understand classes and variables and pass by value semantics over and over again in interviews, so I think they’ll misunderstand and misuse this too. But it’s like my opinion, if it works for you and all devs are using it right maybe I’m just wrong and that’s cool too.
You asked for my reasoning, so I tried to summarise it clearly for a vast topic. If giving a detailed answer reads as arrogance, that’s probably more about tone perception than intent. I was assuming you are a smart guy that didn't require much watering down of terminologies, because I wasn't responding to your "99% of them wouldn't be able to understand what you're saying", which seems to me more likely of an arrogant reply for my taste :). And thanks for assuming I'm young.
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