When designing an event, is it a good idea to prevent listeners from being added twice?
- by Matt
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.