Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In designing an API that provides an event listening interface, it seems there are two conflicting ways of treating calls to add/remove listeners:

  1. Multiple calls to addListener will only add a single listener (like adding it to a set); can be removed with a single call to removeListener.

  2. Multiple calls to addListener will add a listener each time (like adding it to a list); must be balanced by multiple calls to removeListener.

I've found an example of each: (1) - The DOM addEventListener call in browsers only adds listeners once, silently ignoring requests to add the same listener a second time and (2) - jQuery .on behaviour adds listeners multiple times.

Most other listener APIs seem to use (2), such as SWT and Swing event listeners. If (1) is chosen, there's also the question of whether it should fail silently or with an error when there is a request to add the same listener twice.

In my implementations, I tend to stick with (2) since it provides a cleaner setup/teardown type interface and reveals bugs where 'setup' is unintentionally being done twice, and is consistent with most implementations I've seen.

This leads me to my question - Is there a particular architecture or other underlying design that lends itself better to the other implementation? (ie: why does the other pattern exist?)

share|improve this question
To clarify: consider addListener(foo); addListener(foo); addListener(bar);. Does your case #1 one add one foo and one bar, or only bar (i.e., bar overwrites foo as the listener)? In case #2, would foo fire twice, or once? – apsillers Jan 2 '13 at 17:55
The implementations of case #1 that I'm familiar with generally go by reference - if foo == bar, then it would overwrite, otherwise, it would have one foo and one bar as listeners. If it always overwrote, it wouldn't be a set, but a single object that represented an observer. – Krease Jan 2 '13 at 17:59
(2) won't reveal any bugs as long as you don't forbid adding the same listener twice - and then there is no real difference to (1). – Doc Brown Jan 2 '13 at 18:01
The choice should be dependent on the requirements of your API users, so normally it would be best to ask one of them. When you now make a design decision, and one of the users uses your API and tells you the design does not work good for him, do you have a chance to change that decision later on? – Doc Brown Jan 2 '13 at 18:11
@DocBrown - in the specific case that is the reason I asked the question, we don't have much option to change. I know it's not a huge deal to use one option or the other, so the question is more of a conceptual one - are there any reasons based on architecture/design/reliability (ie: besides user preferences) to choose one pattern over the other? – Krease Jan 2 '13 at 19:27
up vote 2 down vote accepted

If you've got some events which you're running into problems with managing the add/removes, I would start adding IDs.

Add a listener returns an ID, the class that added it keeps track of the ID's for the listeners it's added and when it needs to remove them, it calls remove listener with that/those unique ID(s).

This puts the consumers in control so that they can get compliance with Principle of Least Astonishment in the behaviour.

This means adding the same one twice adds it twice, gives a different ID for each one, and removal by ID removes only the one associated with that ID. Anyone consuming the API would expect this behaviour when they saw the sigs.

A further addition in violation of YAGNI would be a GetIds where you hand it a listener and it returns a list of IDs associated with that listener if it is capable of getting appropriate equality checks, though that is dependent on your language: is it reference equality, type equality, value equality, etc? you have to be careful here because you may return IDs which that consumer should not be removing or meddling with, therefore this exposure get's dangerous and is ill-advised and should be unnecessary, but GetIDs is a possible addenda if you're feeling lucky.

share|improve this answer
There's not necessarily an issue where there are problems with adds/removes (as the question should apply to any program, not just the one I'm working on), though I definitely see how this pattern would specifically make it clear that the API is using option #2 (or a slight variation of it, where removal is by id instead of by listener) – Krease Jan 2 '13 at 19:35
Having a subscription return an object that can be used for unsubsciption is, IMHO, the right approach. In object-oriented frameworks with IDisposable, Autocloseable, or other such interface, the unsubscription object should implement that interface in thread-safe fashion (always possible--if nothing else by placing the subscriber within the unsubscribe object itself, and having its unsubscribe method invalidate that reference, and having subscribe requests occasionally scan the subscription list for dead subscriptions). – supercat Mar 3 '14 at 20:50

First, I would choose an approach where the order in which the listeners are added is exactly the order they will be called when the related events are triggered. If you decide to go with (1), that will mean you use an ordered set, not just a set.

Second, you should clarify a general design goal: shall your API more follow a "crash early" strategy, or an "error forgiving" strategy? This depends on the usage environment and the usage scenarios of your API. Generally, (developing mainly desktop apps) I prefer "crash early", but sometimes it is better to tolerate some kind of errors to make the usage of an API more smooth. The requirements, for example, in embbeded apps or server apps may be different. Perhaps you discuss this with one of your potential API users?

For a "crash early" strategy, use (2), but forbid adding the same listener twice, throw an exeption if a listener is added again. Also throw an exception if one tries to remove a listener not in the list.

If you think an "error forgiving" strategy is more appropriate in your case, you could either

  • ignore the double adding of the same listener to the list - which is option (1) -, or

  • append it to the list like in (2), so it will be called twice when the events are fired

  • or you append it, but don't call the same listener twice in case of event-triggering

Note that the listener removal should correspond to that - if you ignore double adding, you should also ignore double removal. If you allow the same listener to be added twice, it should be clear which of the two listener entries is going to be removed when one calls removeListener(foo). The last of the three bullets is most probably the least error-prone approach among those suggestions, so in case of an "error forgiving" strategy, I would go with that.

share|improve this answer
My main strategy so far has been to 'use a similar pattern to the surrounding environment' - ie: the most common pattern used in the rest of the code/language I'm integrating with. The 'crash early' strategy would definitely catch a lot of potential issues, but I've never actually seen this used in practice, so it might be surprising to an API user (though the more I think about it, I'd consider it a 'good' surprise since it would help catch bugs) – Krease Jan 2 '13 at 19:43
@Chris: I am pretty sure you have seen "crash early" a lot. For example, in most modern mainstream languages, you get exceptions when you try to write out of array bounds, try to convert strings to numbers which are not convertible and so on. – Doc Brown Jan 3 '13 at 9:45
I was referring to it specifically in the context of the listener pattern – Krease Jan 3 '13 at 15:45

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.