views:

161

answers:

3

Should an addListener method check for duplicate registrations when called? If so, what should happen when a duplicate is found?

final public class exampleCanFire {
    public void addFooListener(FooListener listener) {
      // Before adding listener to private list of listeners, should I check for duplicates?
    }
}
+2  A: 

I don't think there is a specified behaviour for detecting duplicate listeners. I would say, unless you're writing an event handling framework it's probably better not to bother checking. If a class registers itself as a listener twice, it's a bug in the calling code and not in the observable object.

If you did want to do something I'd just suggest throwing an IllegalArgumentException stating the message that you cannot register the same listener twice.

Phill Sacre
A: 

Store them in a Set, and propagate whatever the Set's response is:

Set<FooListener> listeners = new HashSet<FooListener>();

public boolean addFooListener(FooListener listener) {
  return listeners.add(listener);
}
Zed
+4  A: 

My preference is to store them in a List and not check for duplicates. Some advantages of this approach:

  • Listeners are notified in a deterministic order and could potentially mark events as "consumed" causing them not to propagate to subsequent listeners.
  • One can use the CopyOnWriteArrayList implementation, which allows a listener to remove itself during a notification callback without a ConcurrentModificationException being thrown (this is very important and is a classic gotcha when writing event oriented code).
Adamski
+1 for the `CopyOnWriteArrayList`.
Bombe