JDEP183H
Handout 19: Detour – Why Event-Driven Programming
October 3, 2006
Traditional, Procedural
Solution to Event Handling
Consider the
following pseudocode:
while (operating) {
if (eventA) then
process eventA
if (eventB) then
process eventB
...
if (eventZ) then
process eventZ
}
Suppose that at the
time when the program checked for the occurrence of eventA at time t, eventA was not observed to have
occurred. However, when the program
proceeded to check for the occurrence of eventB at time t+δ, eventA took place.
However, the program did not check for eventA at time t+δ. Instead, the program would go through all its
checks before iterating the loop, and only then, would the program realize that
eventA had taken place. Also, with the
above pseudocode, we see that the programmer actually imposes an order (a
sequence) on how events are expected to occur, which may not be what the users
have in mind.
This is how
traditionally event handling works. As a
result, the GUI or the application is not responsive
enough. If there are many events to check for, it could take the
application such a long time to respond to an event that the application is no
longer user-friendly. In a sense,
traditional solutions do not conveniently allow for timely “detours”.
Java’s Delegation-Based
Event Handling
In Java, however, we set up the event sources, attach to each event
source an event listener, and implement for each event an event handler. At run time, these listeners are all active
simultaneously, listening for specific events at the same time. Thus, events are handled in the first-come
first serve manner. This significantly
increases the responsiveness of event handling.
Further, with Java’s delegation model, client programmers like us do not
need to use while loops to listen for events.
Once activated, the listeners will do that for us.