|
The Event-driven paradigm
CptS 355 - Programming Language Design Washington State University |
|
EventsSimilar to an exception, an event is a (hardware) condition that is signaled. Unlike an exception, an event is a normal, expected condition. Common events are from input devices, such as
while (TRUE) { // loop forever
while (empty(event.queue)); // wait for an event
event = pop(event.queue);
(lookupHandler(event))(event.information);
}
// a mouseDown event handler
public boolean mouseDown(Event event, int int x, int y) {
// what to do on a mouse down
}
// a buttonDown event handler
buttonDown(button b) {
// what to do on a button down
}
Another style of event-driven programming embeds the main loop in the
GUI framework so all the programmer does is register handlers then tell
the framework to start processing events. The Java swing framework
is of this flavor. I consider it better. Why?
If the programmer provides the main loop there is a strong temptation
to write the processing code inline in the loop which, without discipline,
can lead to unnecessary and undocumented coupling between the event handlers.
If event handlers are registered methods the coupling has to be made clear (and
hopefully that results in less of it.)
|
|