The Optional wasn’t designed to be used as a input.
The Optional was designed to the an output.
It’s like a container that may or may not have a non-null value in returns.
An alternative to return null.
To avoid obj == null, more objective, avoiding NPE.
Even though you can use it as an input method.
Because you like Kotlin and want to use Java as Kotlin… don’t do that.
People argue that:
we’ll use Optional as input to avoid NPE.
Dude, really?
We’ve many other ways to validate an input method in Java.
Did you heard about “Jakarta Validation”?
Using Optional as input can lead to designs like this (simplified):
1 | |
That’s clearly a bad design!
Why do you have an Optional input?
It’ll be more confusing if you try(you do it, right?) to create a test.
1 | |
Pay attention about how ugly they are.
1st make a boundary in your method, only allow get into the method valid state.
Just by @NotBlank you you not allow null or blank.
1 | |
2nd use Optional as it should be used, as output:
1 | |
The code is:
- a way clean
- has an effective boundary about what
stateis expected to get inside method - readable
- objective
Use the API as it’s intended to be.
Use it correctly, be smart, don’t force “similar” behavior where it doesn’t apply.
Java is beautiful, so create clean and more maintainable code.
xoff.