I've been reading articles on beeing null safe in java, and how it's bad to return null
, or of that sin, that is passing null
as an argument. I get that it simplifies life, and people don't always read documentation, so they don't know wheather a method can return null
, or if null
can be passed to it. Annotations seem to just pollute the code, and there is no Kotlin-like null safety mechanism. In my current project I try to design everything in such a manner, that null is almost unnecessary, at least for the end-user.
I want to create a change listener (something like javafx.beans.value.ChangeListener
), such that i can pass a previous and a current value to the changed()
method. The thing is, I want it to be null safe, so I don't want to ever pass a null
as an argument, even though it can change from no value to some value, or from some value to no value. I could add two additional methods for that situation and have something like:
public inteface ChangeListener<T> {
void valueSet(T current);
void valueChanged(T previous, T current);
void valueCleared(T previous);
}
This approach seems excessive though. I could also use
java.util.Optional<T>
as arguments, but that adds additional boxing:
public inteface ChangeListener<T> {
void changed(Optional<T> previous, Optional<T> current);
}
Is there a more elegant option? Or should I force user to use some sort of a Null Object Pattern? Although that will create problems with the need to extend some classes. I could also stop caring, specify in the documentation what will happen if null
is used, and let the user find the source of all the NullPointerExceptions.