Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In both your examples, there seemed to be a logical default value (eg. if it's required to be positive, negative numbers turn into 0). Assuming you document that well (what the defaults are if the value is invalid), I think your first approach seems like it's on the right path.</p> <p>I'd recommend starting with a concrete class like <code>SimpleIntegerProperty</code> as the class you're extending (unless there's some reason you chose <code>IntegerPropertyBase</code> instead.</p> <p>I would then overwrite both the <code>set(int)</code> method and the <code>setValue(Number)</code> method, wrapping the parent in your logic:</p> <pre><code> /** * Explanation that values under 0 are set to 0 */ @Override public void set(int value){ super.set(value &gt; 0 ? value : 0); } /** * Explanation that values under 0 are set to 0 */ @Override public void setValue(Number value){ super.setValue(value.intValue() &gt; 0 ? value : 0); } </code></pre> <p>There may be a case where there isn't logical default values (or you just want to reject invalid values). That case makes it a bit harder - you'd actually want to use a method signature of like this so the caller knows if the value changed:</p> <pre><code>public boolean set(int value) </code></pre> <p>In order to do that, you'll have to go back quite a few classes - all the way back to <code>ReadOnlyIntegerProperty</code> and implement the setting / invalidating structure yourself.</p> <p>I would hesitate to use Exceptions to handle the invalid input. It is a legitimate use of exceptions, but my fear is that the Exception would be relied on for validation. Exceptions are very resource intensive, and should only be hit if there's 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 validate before sending to you).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload