Image goes here
The Event-driven paradigm
CptS 355 - Programming Language Design
Washington State University

Events

Similar 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
  • mouse events - mouse up, mouse down, mouse move
  • keyboard events - key up, key down
  • network events - packet arrival
  • window events - window resized, window dragged, focus lost
Special hardware detects and signals these events. Each event has additional information. For example a mouse movement event has an x and y coordinate. In a Graphical User Interface (GUI), there exist widgets which are high-level events constructed from low-level events in specific areas.
  • button down - mouse down, mouse up in a particular screen area
  • check-box - mouse down, mouse up in a rectangular area
  • radio-box - mouse down, mouse up in a rectangular area
  • text-area - keyboard events in a scrolling text field
There is special hardware support for graphics. At a higher-language level, operations (typically function calls or methods on a graphics object) are provided. In a language that supports exception handlers, flow-of-control switches to the handlers when an exception is raised, and the the normal flow-of-control resumes. In event-driven programming, there is essentially no normal flow-of-control! Only the event (exception) handlers exist. Flow-of-control is entirely driven by responding to events. The event dispatcher is called the main loop.
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.)
(c) 2003 Curtis Dyreson, (c) 2004-2006 Carl H. Hauser           E-mail questions or comments to Prof. Carl Hauser