Forbid null (or return default value) in JavaFX SimpleObjectProperty

I have a class with a SimpleObjectProperty<SomeFunctionalInterface> member. I don't want to clutter my code with any null checks on its value; instead I have a default implementation of SomeFunctionalInterface, the only method of which is simply empty. At the present, I assign this default value as the initial value of the property, and also have a change listener on the property which sets the value of the property back to the default implementation if anyone attempts to set its value to null. This, however, feels a bit clunky, and setting a thing's value from inside its change listener makes me feel dirty.

Short of creating my own class extending SimpleObjectProperty, are there any ways of getting an object property to return some predefined default value if its current value is null?

Upvotes: 1

Views: 538

Answers (1)

James_D
James_D

Reputation: 209388

You could expose a non-null binding to the property:

public class SomeBean {

    private final ObjectProperty<SomeFunctionalInterface> value = new SimpleObjectProperty<>();

    private final SomeFunctionalInterface defaultValue = () -> {} ;

    private final Binding<SomeFunctionalInterface> nonNullBinding = Bindings.createObjectBinding(() -> {
        SomeFunctionalInterface val = value.get();
        return val == null ? defaultValue : val ;
    }, property);

    public final Binding<SomeFunctionalInterface> valueProperty() {
        return nonNullBinding ;
    }

    public final SomeFunctionalInterface getValue() {
        return valueProperty().getValue();
    }

    public final void setValue(SomeFunctionalInterface value) {
        valueProperty.set(value);
    }

    // ...
}

This won't work for all use cases, but may suffice for what you need.

Upvotes: 2

Related Questions