views:

59

answers:

2

I am creating an event-based API where a user can subscribe to an event by adding listener objects (as is common in Java or C#). When the event is raised, all subscribed listeners are invoked with the event information.

I initially decided to prevent adding an event listener more than once. If a listener is added that already exists in the listener collection, it is not added again. However, after thinking about it some more, it doesn't seem that most event-based structures actually prevent this. Was my initial instinct wrong? I'm not sure which way to go here. I guess I thought that preventing addition of an existing listener would help to avoid a common programming error. Then again, it could also hide a bug that would lead to code being run multiple times when it shouldn't.

+1  A: 

I agree with Henk, but then again, it's simpler to unregister a callback if there is only one of it. Otherwise you either have to specify that the last or first one will be removed, or it's arbitrary. Java's Observable class works this way, if an Observer is already in the list, addObserver with that Observer is a no-op. Then again, in my Python code I just remove the last copy of the observer from the list, and allow duplicates, I've just never found a good use case that depends on either strategy.

Longpoke
I had forgotten about Observable. I guess it can go either way, then.
Matt
A: 

I appreciate the answers that have been given, but I think I will just go with preventing the same listener from being added more than once. Java's Observable behaves this way, and I am using a CopyOnWriteArrayList as the backing collection for the listeners which already has this available (addIfAbsent()). It just seems less likely that someone would really wish to add the same listener multiple times, and it is simple to achieve the same behavior by either creating another listener or using iteration within the same listener. I can understand the arguments for allowing duplicates (hence my doubts), but not strongly enough to change it.

Matt