Why JavaFX properties have not getListeners() methods

Viewed 1160

I am using JavaFX properties since JavaFX 8.0 , they seem to miss something appropriate i think . Let's say i add a change listener to a JavaFX Property :

 DoubleProperty doubleProp = new SimpleDoubleProperty(1);
 doubleProp.addListener((observable,oldValue,newValue)->{ ...code here }));

and i want to add 3 more including and InvalidationListener

Why to create an instances of ChangeListenerJavaDoc or InvalidationListenerJavaDoc?

Adding lines of code like :

 ChangeListener<? super Number> listener = (observable , oldValue , newValue) -> {
                    if (newValue.intValue() == 1)
                        //..... code
                };

all over the place isn't clear.


Why methods like these doesn't exist:

doubleProp.getChangeListeners().clearAll();

or

doubleProp.getChangeListeners().remove(doubleProp.getChangeListeners().get(0));

or

doubleProp.remove(doubleProp.getChangeListeners().get(0));

or

doubleProp.getInvalidationListeners().get(0));

Does JavaFX 9.0 has methods like these ? Is what i want a bad design ? I need to know the above :).

2 Answers

@James_D, your explanation about what can go wrong when a listener is carelessly removed is good. However, this is really a developer problem, not design. Indeed, it is bad design for any 'add/remove' pattern not to also include access to whatever has been added.

For example, it may be useful to remove ("suspend") all the listeners temporarily in order to perform a process that changes the value (indeed several times) where the value at the end of the process is the same as the start; when the process is finished the listeners are added back ("restored"). While the 'reference' solution works for listeners you know about when designing a control, it doesn't help for listeners added by a developer using your control - these can't be referenced because you don't know what they will be. The 'suspend/restore' technique deals with this, it's up to the developer to use it properly and in the right situation.

JavaFX's property enhancements (object properties, bindings etc) are a huge improvement over Swing, like moving from a covered wagon to a Bugatti. However, the omission of a 'getListeners()' feature is a drawback.

Related