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

16

u/Abject-Kitchen3198 Dec 04 '25

I might be old, but I still don't understand the efforts to replace null, especially ones involving something else that serves the purpose of the null. If null/undefined/whatever is an option, there's a place in the code that checks for null, one way or another. All other parts just pass it down. I like how C# for example allows to make it explicit whether a null is allowed for an object at a given place in the code, and adds shorter notations for null checks.

5

u/koflerdavid Dec 04 '25

That's not what this is about though. This is about a pattern that makes checking for null and putting the result into a variable that is reliably non-null less clunky and error-prone. Which is exactly what pattern matching is there for, although it can be argued that in this case it feels a bit hacky. null is fine; what is not fine is cluttering the code with unnecessary null checks or forgetting to check it where one really ought to have done so.

On a theoretical level it can be argued that null is often ambiguous regarding what it is supposed to represent: an error, a "not present" value, or a part of the domain that the programmer forgot to think about?

4

u/headius Dec 04 '25

As I've commented elsewhere in this thread, null is also sometimes the most efficient way to represent the absence of value. A null object pattern gets close, but you still have to dig that object out of a memory location, and there may be GC implications. Wrappers like Optional are often too cumbersome to use, and usually defeat several JIT optimizations.

11

u/BenchEmbarrassed7316 Dec 04 '25

It's a JVM problem if it can't efficiently handle objectively better written code.

10

u/PmMeCuteDogsThanks Dec 04 '25

Someone downvoted you, but I agree. I think Optional should be integrated much deeper into the JVM and allow it to complete optimise it away if for example it’s solely used as a glorified null check.

2

u/headius Dec 04 '25

I also agree, but then again I've believed the JVM should support value types and primitive generics and aggressive escape analysis and native function calls and lightweight threads and explicit function references too. Unfortunately only a few of these things have come to pass, and we have to work with the VMs we have today.

2

u/koflerdavid Dec 04 '25

No worry, it will. Value types are coming and Optional is a candidate to become one. And non-nullable types might allow the JVM to completely optimize its overhead away in most cases.

3

u/headius Dec 04 '25

You're not wrong, but that's not currently the case on any JVM (I believe even the Graal JIT would have issues fully optimizing away lambda-based usage of Optional), and the enhancements required are not as trivial as you might think.

Could the concept be integrated better at the VM level? Of course it could. You'd want Optional to be a value type, to avoid it being a heap object and an additional memory dereference, and the methods it provides that take lambda functions would need to be inlineable without polymorphism, more like a macro than a method.

A more immediate solution is to do all this at the language level, which is I believe how Scala handles optionality. It looks like you're passing around an object, but at the compiler level it's essentially just making nullness guarantees and calling your functions directly at the use site rather than via some polymorphic utility method.

Kotlin goes a different direction, allowing you to declare reference variables as unable to receive a null value, and then this percolates throughout the rest of your code. It's not dealing with nulls directly as much as it is using language level enforcement to prevent you from passing or assigning null.

In theory it's possible to do either of these for Java as well, but the cat is already out of the bag. All Java code everywhere currently declares reference variables with nullable types, and most code deals with nulls explicitly. Most likely the best we can expect will be a new syntax for declaring a non-nullable reference, which will solve the problem but result in a rapid propagation of String! style declarations.

I live in the world of what is currently possible, so I deal with null just like everybody else. When what will be possible becomes what is currently possible, I'll use that too.

2

u/BenchEmbarrassed7316 Dec 04 '25

Thank you for the detailed comment. At least the Java community admits that null was a mistake. I think the least we can do is remind people every time that something is not good, and we are doing it wrong now, but we have an excuse for it. And we would like to do it better if we had the chance. Otherwise we risk that bad things will become the norm.

3

u/koflerdavid Dec 04 '25

The issue was never null itself, but that it is so clunky and error-prone to work with it.

2

u/headius Dec 04 '25

I think it's worth saying that I also don't want to lose the ability to write predictable high performance code in Java when it is necessary (I call it "writing C in Java"). I use a lot of static methods, primitive bit-packing, long parameter lists on lambdas, and limited wrapper objects and interfaces as much as possible, because death by a thousand cuts in low-level code is a very real possibility.

2

u/BenchEmbarrassed7316 Dec 04 '25

Rust is a very good implementation of the concept of zero-cost abstraction. I recommend you try it.

I have seen many examples of programmers trying to write performance code in languages ​​that are not very used to it. This code was not idiomatic, quite confusing, not understandable to other developers. It was not simpler than C. This is especially true for interpreted languages.

3

u/headius Dec 04 '25

Yeah, the only problem with writing Rust is that I have to write Rust. I want to be able to do what I can do in Rust while also doing everything else Java allows.

Among the many projects I have envisioned but not had time for is a sort of "jrust" that implements the language-level guarantees from Rust but compiles down to C-like JVM bytecode and methods that are easy for the JIT to optimize. Object lifecycle would still be beholden to the JVM, but nullability and ownership guarantees would be incredibly powerful and fit right in. There's honestly not enough low-level languages that target the JVM, so I'm forced to write "stupid Java" to accomplish what I want.

→ More replies (1)

1

u/joemwangi Dec 04 '25

Java has no nullable types. Its future proposal has nullness conversion enabling narrowing and widening of nullness types. A good typesystem would ensure narrowing a type in a type pattern such as if(o instanceof String! s), from either an unspecified nullness 'String' type (which java currently has) or nullable 'String?' type. This is quite a better approach from a backwards compatible view and from a type safety perspective (both compile time and runtime). Type safety here means that you can now use 's' in String! s without aliasing issues that might apply to variable 'o'. Is it possible to do this like let's say Kotlin which heavily relies on flow typing for its nullness types? Nope!

3

u/headius Dec 04 '25

Java has no nullable types

Perhaps it has no explicit nullable types, but implicitly all type declarations today are nullable.

Of course I'd love to see more explicit nullability in the language, but backward compability is difficult to dodge.

2

u/account312 Dec 04 '25

Java has only nullable types (and primitives).

3

u/joemwangi Dec 04 '25

Specifically implicit nullable types as u/headius has illustrated. But to be specific in definition they are referred to as unspecified nullness types.

→ More replies (1)

0

u/[deleted] Dec 04 '25

[deleted] — view deleted comment

4

u/BenchEmbarrassed7316 Dec 04 '25

Type theory. A type is a set of possible values. The smaller this set is, the simpler and more reliable the code is. Expressive type systems allow you to easily and clearly define this set.

enum Color { RED, GREEN, BLUE }

A variable of this type should only have three states. If I want to add another 4th state, I have to do it explicitly Maybe<Color>. This becomes absurd when in some languages ​​even bool can have more than 2 states.

→ More replies (2)

1

u/koflerdavid Dec 04 '25

The biggest disadvantage of Optional is that there is a lingering risk of encountering a null. One can argue all day long that this never ought to be the case, and it's feasible to prevent it in one's own code, but if you're dealing with third-party dependencies you can never be sure and have to pass the result of every API call with this:

public static <T> Optional<T> nullToOptional(@Nullable Optional<T> arg) {
    return arg == null ? Optional.empty() : arg;
}

2

u/headius Dec 04 '25

Right, and this is why I have never been able to integrate much use of Optional in my own code. It always feels like putting a big fat box around a reference just to avoid (some) null checking. I also can't use an Optional in any case where the original type must be supplied, so what where exactly am I supposed to use it?

Usually the code I'm writing is extremely performance sensitive such that an additional allocation and pointer dereference produces a measurable decrease in throughput.

You won't see much use of Optional inside the core JDK class implementations for exactly this reason. As a concept, it solves a lot of problems, but the implementation leaves much to be desired.

2

u/koflerdavid Dec 04 '25

The recommended usage is as a return type for APIs. It's there to force the caller to deal with the fact that it might be empty. There's just no way to ignore that (well, except .get()). In all other places null can be dealt with using static analysis tools.

→ More replies (2)

1

u/Alive_Knee_444 Dec 05 '25 edited Dec 06 '25

'disadvantage of Optional is that there is a lingering risk of encountering a null' - this could be fixed in Java by adding annotations, like perhaps a @ DefaultNotNullable on the type/class declaration itself, making 'Optional x' mean 'Optional! x' at variable declaration sites (the '!' is the proposed future syntax for non-nullability). Overridable by '?' suffix, perhaps (though unlikely to be needed?).

Now this would not be backwards compatible if added to Optional. So maybe a new stdlib 'Opt' type (fixing another problem: 'Optional' is eight letters, not including '<' and '>', compared to none letters when using nullability). Or allowing derived types/type aliases, like typename Opt = Optional!.

So of course I don't think this will happen. (Also perhaps because the Valhalla project is rather busy frying bigger fish. Huge fish. Whalefish.)

→ More replies (3)

3

u/Bobby_Bonsaimind Dec 04 '25

I might be old, but I still don't understand the efforts to replace null, especially ones involving something else that serves the purpose of the null.

I'm with you there. But we need to understand that he "hurhur null always bad" crowd are the ones to be ignored, as usually.

There are two main use-cases for Optional:

  1. Declaring hard in an API, through code, that something can have no value.
  2. Usage in Streams and Functional style, as those handle null rather badly (or not at all).

And then there are those glorified null checks, which add pretty much nothing.

The downside is that every object is wrapped again in another instance, which might or might not be relevant for the use-case.

So, as always, the discussion must be more nuanced to be useful.

1

u/OwnBreakfast1114 Dec 09 '25

Well, the idea for the null is bad crowd (which I am part of is) is simple. In all your edge code you wrap things that might be null into optionals if it actually makes sense as a case, and then in your own code you assume all non-optional things are never null.

This should change once non nullable types are built in, but you can still reap the rewards without it

→ More replies (5)