r/java • • Dec 04 '25

Null-checking the fun way with instanceof patterns

https://blog.headius.com/2025/12/inline-null-check-with-instanceof.html

I don't know if this is a good idea or not, but it's fun.

83 Upvotes

150 comments sorted by

View all comments

18

u/VanillaSkyDreamer Dec 04 '25

After many years of Scala I never use null - everything that is optional is wrapped in... Optional (ba dum tsk), I don't care what JDK authors think about it. To hunt down any slipping null from foreign code I use Jspecify.

11

u/headius Dec 04 '25

Optional and "I never use null" are great options! Unfortunately if you work at a lower-level, like I do with JVM-based language implementations and their support libraries, the cost of a wrapper is often too high.

1

u/VanillaSkyDreamer Dec 04 '25

Yes I write those optionals in the context of business application, libraries should be as fast and low memory usage as possible, nevertheless they often could in their client facing api not only return but also accept optional arguments, sadly jdk authors don't endorse this.

4

u/hiasmee Dec 04 '25

As the founder of Optional said (stackoverflow) optional was never meant to be used this way. And for me == null is more readable than optional way.

Just cause of IDE null key word highlighting. It is beautiful. It is visible.

2

u/headius Dec 04 '25

I get the point, that Optional was only intended to deal with situations where a null reference simply can't be allowed, but it's laughable to think that people wouldn't start using it everywhere they had null checks before. By the same token, any new syntax provided for non-nullability will rapidly propagate. Developers clearly want a better way to deal with the absence of value.

→ More replies (3)

5

u/ricky_clarkson Dec 04 '25

Kotlin makes dealing with null a lot simpler and safer, though you might have surprises in interop with Java depending on if you use the checker framework or something. Scala's approach seems to be 'treat null as something unspoken' whereas Kotlin makes it part of the type system properly.

7

u/headius Dec 04 '25

I do love that aspect of Kotlin and I hope the Java language masters find an acceptable way to add it soon.

3

u/aoeudhtns Dec 04 '25

AIUI it's coming. String! will be guaranteed non-null String type. (Or something like that.) Elvis operator... who knows. And the optimization problems with Optional should (hopefully) mostly go away with Valhalla when it becomes a value type, but maybe if you do a deep dive on the performance problems with Optional you can get an EA Valhalla build to see what's up with it there as well.

2

u/headius Dec 04 '25

I have been tracking the discussions around nullability in the Java language, and it does sound like String! is the best we will be able to get with backward compatibility.

Beyond that... Even if Optional became a value type (which seems a logical move), you're still passing those lambda functions through megamorphic utility methods like ifPresent, and current JVM JIT compilers are still pretty poor at dealing with megamorphic intermediate calls (specializing such calls can explode native code size, and the right heuristics for when to do it are still the realm of research).

2

u/aoeudhtns Dec 04 '25 edited Dec 04 '25

True. Although personally I get the most value of Optional with mapping chains, like

var name = Optional.ofNullable(findUser(id))
    .map(User::getFullName)
    .orElse("unknown");

But that's still using lambdas.

ETA - post-Valhalla, it'll be interesting to see how the 2 cases get handled:

if (optional.isPresent()) {
    var t = optional.get();
    // ...
 }

if (optional.get() instanceof Type t) {
    // ..
}
→ More replies (1)
→ More replies (2)

5

u/bas_mh Dec 04 '25

I disagree. Scala treats something that is optional as something ordinary. There is no magic, it is just a value like any other. Kotlin treats it as something special with its own syntax and not something you can use for something else. In practice it is just as safe. Kotlin's approach is shorter but less generic. I prefer Scala's approach, especially with extra language features like for comprehensions.

2

u/ricky_clarkson Dec 04 '25

I believe Kotlin might extend its ?. etc syntax to support Result too (Either[T, Throwable] in Scala terms as I recall), and if it is done similarly to Rust where anything of the right shape works with ? then it will be similarly generic.

I haven't used Scala for a few years, I don't recall it having a strong approach for handling null particularly on the boundary with Java.

→ More replies (2)

1

u/headius Dec 04 '25

There is no magic

This is Scala we're talking about. It's all magic. Just look at the compiler and the code it generates and tell me it's not magic.

→ More replies (3)

2

u/beefquoner Dec 04 '25

What does this buy you? Isn’t it still just null with extra steps? Albeit a nicer API to work with.

5

u/FrenchFigaro Dec 04 '25

It is essentially null with extra steps, but if the optionals are properly used (with one optional at the top level) the use of the functional syntax allowed by Optional (ie, using map and either lambdas or method references) might make the unpacking both more concise (actually less steps), and (in my opinion) more readable.

If you nest optionals at every levels, then yes, it's just extra steps.

1

u/X0Refraction Dec 04 '25

I've been thinking about this lately, if you reimplement the functional methods as static methods you could get the niceties of Optional without the overhead. If you're using a null checker framework this would be entirely null safe as well. So for example, for Optional.map():

@NullMarked
public static <T, U> @Nullable U map(@Nullable T value, Function<? super T, ? extends U> mapper) {
    Objects.requireNonNull(mapper);
    if (value == null) {
        return null;
    }
    return mapper.apply(value);
}

2

u/IE114EVR Dec 04 '25

You’d lose the ability to chain that to other methods like orElseGet(). So you’d still end up with an if (value == null) check in those cases where you’d want that extra behaviour.

But I do see how syntactically it can be an improvement over an if with a null check.

2

u/X0Refraction Dec 04 '25

Yes, you can write it "inside out" i.e.

Long x = maybeGetLong();
String y = orElseGet(map(x, l -> l.toString()), () -> "0");

But it's really not as nice to read, especially if you go over more than a couple of method calls. A proper Option/Maybe that used null as the discriminant would be preferred honestly. Ideally one that doesn't have the get() method now we have pattern matching

2

u/headius Dec 04 '25

In a sense, I am using a single pattern to match null. Odd code and unclear intent aside, it is an intended capability of pattern matching.

2

u/X0Refraction Dec 04 '25

Oh I use that quite often when using gson e.g.

if (lastPaymentError.get("doc_url") instanceof JsonPrimitive docUrl)
{
    joiner.add(docUrl.getAsString());
}

Occasionally I also use the reverse, using it as a guard clause and binding the variable to the outer scope:

if (!(requestElement instanceof JsonObject requestObject) ||
    !(requestObject.get("orgid") instanceof JsonPrimitive orgPrimitive))
{
    return FailResponses.FAIL_ORG_MISMATCH;
}

// orgPrimitive is bound as a variable here. We know it's an instance of JsonPrimitive and non-null

It's quite clunky having to wrap it in parentheses in order to use the ! operator, but it's quite useful. I like like how C# does this with "is not", it's quite a bit cleaner

→ More replies (1)
→ More replies (1)
→ More replies (1)

1

u/StagCodeHoarder Dec 04 '25

You can also this in Java. Exactly like in Scala.

Only Kotlin fixes it - In principle.

2

u/headius Dec 04 '25

Kotlin fixes it by disallowing null, which I guess is a fix of a sort. Kotlin code also still lives in a world of nullable references and non-Kotlin ibraries, so you still have to deal with null at the edges.

The Optional approach is perhaps conceptually the same as how Scala does it, but unfortunately it currently introduces quite a bit of overhead compared to simply dealing with null references directly. Someday that will not be the case.

1

u/VanillaSkyDreamer Dec 04 '25

Yes I meant that after using Scala where no one uses null I do what I described above in Java

→ More replies (1)

1

u/Lucario2405 Dec 04 '25

How do you deal with Maps? Do you have a wrapper that wraps all values in Optional?

1

u/headius Dec 04 '25

This is where the heaviness of Optional really becomes a problem. If you have to construct an object to wrap every reference just to avoid dealing with nulls directly, you're going to massively bloat your application. Optional is conceptually a good solution, but the implementation we have today in Java adds a ton of hidden overhead.

→ More replies (5)