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.
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
CopyOnWriteArrayListas 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.