Sunday, July 8, 2012

What is the difference between callbacks and listeners?



Callback. The other code tells the developer: Hey, if this event occurs, I'll call the function in this bucket. You must know where the bucket is to connect your callback.

Listeners. The other code tells the developer: Hey, if this thing occurs, I'll send this event. You can connect your handler (hopefully) where it makes sense to you.

Explanation 1:


A callback is procedure you pass as an argument to another procedure. The procedure receiving the parameter can call it, or share it so some other procedures in the system can call it.

An event handler is a procedure called when an event happens. It can be a callback.
An event handler is a type of callback. It's called whenever an event occurs. The term is usually used in terms of user interfaces where events are things like moving the mouse, clicking something and so on.

Explanation 2:


A listener watches for an event to be fired. For example, a KeyListener waits for KeyEvents, a MessageListener waits for messages to arrive on a queue and so on.

The handler is responsible for dealing with the event. Normally, listeners and handlers go hand-in-hand. For example, the KeyListener tells the ExitHandler that "the letter Q was pressed" and the handler performs logic such as cleaning up resources and exiting the application gracefully. Similary a ButtonClickListener would tell the same ExitHandler that the "Exit button was clicked". So, in this case you have two different events, two different listeners but a single handler.

Explanation 3:


A listener is an object that listens, (and takes actions) upon certain events. I.e. it "listens" for events. Cf. the observer pattern.
Example: The MouseListener in the Java API.

A handler is an object that handles certain things that the client class don't want to deal with. I.e. it "handles" events. A typical scenario is that I provide a handler for a specific event/task as an argument to a constructor.
Example: The MemoryHandler in the Java API.

A concrete difference would be that you can have multiple listeners (just call addXxxxListener several times) while you're only supposed to have a single handler.


2 comments:

  1. Hi, My name is Len from Korea. I would like to translate it to Korean. It is possible ? Thanks I will leave URL when I make it

    ReplyDelete
  2. Thank you. This was very well put. This will help many coders. :-)

    ReplyDelete