Reputation: 37
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.
Upvotes: 2
Views: 565
Reputation: 2691
Be a bit careful when people tell you "XYZ considered harmful". I've seen people do away with constructors altogether in favour of factory methods (such as Optional.of(...)
), but as with everything, there's no single correct answer.
You seem to be struggling with trying to achieve several things (using simple code, having only one method in the listener, not using null values) that are mutually exclusive. So stop worrying and focus on what's important.
If your API users are idiots, and they don't read documentation, that's not really your problem. Null is not something dirty; it means "undefined". What is dubious is to use null if something unexpected happened, like "file not found", which should ideally be dealt with via an exception.
If "undefined" is a correct representation of an unset value in your API, then there's nothing wrong with using null.
Upvotes: 4