-
Notifications
You must be signed in to change notification settings - Fork 721
Description
Binding.withNullRepresentation is currently intended for "protecting" the presentation side of the binding from null values originating from the model side. There are also some cases where protection is needed in the other direction.
One typical example is to deal with the null value that you get from a StringToIntegerConverter if the field value is "". Storing a null in the model would generally be the expected case here, but that isn't possible if the model property is int instead of Integer.
One alternative here is to allow configuring StringToIntegerConverter to return some other value instead of null when the presentation value is "", but that approach has some ambiguity challenges that would need to be considered separately.
In either case, it would also be good to have a solution directly in Binder that would work regardless of any used converter. For this, I would propose a two-argument overload of withNullRepresentation that is also configured with an enum that defines in which direction the null representation conversions should go. The current one-argument overload would be retained to use the current approach of protecting against null values from the model. For the enum name, I'd suggest NullOrigin and the supported values would be MODEL and PRESENTATION.
This would mean that the case with a TextField bound to an int property could be implemented like this:
myBinder.forField(myTextField)
.withConverter(new StringToIntegerConverter())
.withNullRepresentation(0, NullOrigin.PRESENTATION)
.bind("intProperty");
Instead of the enum, a separate method name could also be considered if anyone would have a good name suggestion.
withModelNullRepresentationdoesn't make the direction clear: Does it define how to present anullvalue from the model, or anullvalue going to the model?withNullRepresentationToModelmakes the direction clear, but is quite verbose. Should the other direction bewithNullRepresentation,withNullRepresentationFromModel, orwithNullRepresentationToPresentation?withReverseNullRepresentationis clear if you know thatwithNullRepresentationis the default, but the name is again quite ugly.