A truthiness operator would let the reader know you’re doing a shorthand. Another way to do that would be some truthy function or the currently available operators. For example, instead of some new operator, we could write:
if (isNull(a)) { /* ... */ }
if (a.isNull) { /* ... */ }
if (+a) { /* ... */ }
I wouldn’t consider any of these options better than the plain old
if (a == null) { /* ... */ }
If our goal is to save on typing, we aren’t doing a ton. There’s a slight saving of characters by using the unaryPlus
operator but it’s so easy to type the others that it’s doesn’t seem worth it. Even though I prefer the standard (a == null)
, my second favorite would probably be (a.isNull)
due to my internal voice vocalizing the line as “okay, so then if a is null, then…”–any other form makes me do a little odd translation to that wording.
A dedicated new operator might help over unaryPlus
. We still save the 6 or so characters and we might have an easier time reading it if it’s only used to mean “a is null”.
A new operator, compiler changes, and not more clear to the reader. All of this to save 6-8 characters. It’s true checking for null is a common condition, so maybe we get to save writing those 6 characters in many places around our code–but the price for such a feature still seems a bit costly for so little gained.
If it’s common to be slowed down with writing out a null check then the writing is the real problem. The solution can address tooling the text editing experience instead of trying to change the language. Intellij has live templates and even postfix templates.
With templates, all you need to write a null check is a.nn
which would expand to if (a != null)
, or a.in
which would expand to if (a == null)
. I don’t remember the exact template shorthand since I’m on mobile but you can always add a custom template.
For me, these kinds of tooling and editor support gives enough of a shorthand for the writer without obscuring the rather simple null check of if (a == null)
.
A bit of a side rant here as well. I’ve noticed it’s not uncommon for people to complicate a simple null check. For example people start to write a?.let { }
instead of if (a != null)
. Or they try to implement their own if like higher order function.
There is a time to use the alternates but it’s always good to be aware of the trap of complicating a plain old null check.