In both examples, there seemed to be a logical default value (for example, if it should be positive, negative numbers turn into 0). Assuming you are documenting well (defaults if the value is invalid), I think your first approach seems to be on the right track.
I would recommend starting with a specific class, such as SimpleIntegerProperty , as the class you are extending (unless there are reasons why you chose IntegerPropertyBase ).
I would then overwrite both the set(int) method and the setValue(Number) method, wrapping the parent in your logic:
@Override public void set(int value){ super.set(value > 0 ? value : 0); } @Override public void setValue(Number value){ super.setValue(value.intValue() > 0 ? value : 0); }
There may be times when there are no booleans by default (or you just want to reject invalid values). In this case, it is a little more complicated - you really would like to use a method signature like this so that the caller knows if the value has changed:
public boolean set(int value)
To do this, you will need to return to several classes - right up to ReadOnlyIntegerProperty and implement the configuration / invalidation structure yourself.
I would not use Exceptions to handle invalid input. This is the legal use of exceptions, but I am afraid that the Exception will be used for verification. Exceptions are very resource intensive and should only be hit if there is something that needs to be fixed. So it’s really about your intentions and how much you trust people using your class to do the right thing (and check them before submitting).
source share