Thursday, 10 July 2025

@Nonnull versus @NotNull

A quick small blog...

So, we have two (seemingly) conflicting annotations for the same thing1.

Even people who know exactly when to use what have a chance to pick the wrong one, especially with the use of Code Completion and AI nowadays.

So here's a quick rundown, but the reference below is much more in depth:

import javax.annotation.Nonnull;

@Nonnull
IDEs and Compilers use it for Static Analysis of code. (Though the RetentionPolicy is set to RUNTIME)
import jakarta.validation.constraints.NotNull;

@NotNull
Validation Frameworks (like ORMs) use it during Runtime for checks.

What about Nullable values?

import javax.annotation.Nullable;

@Nullable
IDEs and Compilers use it for Static Analysis of code.

There is no @Nullable available for jakarta.validation.constraints. By default things are nullable, unless explicitly mentioned otherwise.

When not to use @NotNull

The primary really important thing to take away from this is to not do the following:

It might work, your IDE might complain or it might not, but at runtime this will be ignored, unless this method is called by a Framework as mentioned above.

Addendum

Don't use javax.validation.constraints.NotNull. It's been superseded by Jakarta when Oracle moved Java EE to Jakarta. See [2].

Referenties

[1] Medium - Understanding @NotNull vs @Nonnull in Java: A Practical Guide to Null-Safety
https://medium.com/@mesfandiari77/understanding-notnull-vs-nonnull-in-java-a-practical-guide-to-null-safety-5e179e918f37
[2] Medium - Difference between javax.validation and jakarta.validation
https://medium.com/@ovinduuu/difference-between-javax-validation-and-jakarta-validation-df0c6dbe5cb3

Friday, 27 June 2025

Brain fart

Sometimes, when I'm programming, I haven't got a good idea of how to do something. What I do have is a large collection of really bad ideas, that I use when I don't have a good idea.

Apparently, good ideas take time. And sometimes they only happen after trying out some really horrendous ideas.

So, I checked the follwing String expression in Kotlin in, and I got some code review comments on it.

"$description $additionalDescription"

The comment was: "put a trim() on the entire thing, as the additionalDescription, which is provided by the user, can be anything (like for example spaces or just empty)".

And I got stuck on that. I came up with something horrendous like the following:

"${(description + additionalDescription).trim()}"

Of course you can immediately see where I went wrong, but once you get invested in the String template solution, sometimes it's hard to break out of that solution again.

The solution I went for was (obviously):

"$description $additionalDescription".trim()