Jump to content

Event-driven programming

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Bugone (talk | contribs) at 04:17, 10 December 2007 (External links: remove dead link). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Event-driven programming or event-based programming is a computer programming paradigm in which the flow of the program is determined by user actions (mouse clicks, key presses) or messages from other programs. In contrast, in batch programming, the flow is determined by the programmer. Batch programming is the style taught in beginning programming classes while event-driven programming is what is needed in any interactive program. Event-driven programs can be written in any language, although the task is easier in some languages than in others. Some programming environments make the task quite easy, others less so.

Contrast with batch programming

Here are two pseudocode versions of a trivial program to add two numbers:

Batch version

read a number (from the keyboard) and store it in variable A[0]
read a number (from the keyboard) and store it in variable A[1]
print A[0]+A[1]

Event-driven version

set counter K to 0
repeat {
   if a number has been entered (from the keyboard) {
       store in A[K] and increment K
       if K equals 2 print A[0]+A[1] and reset K to 0
   }
}

At first sight, the event-driven program seems more cumbersome and for such a trivial task is indeed so. However, the second program can be generalized far more easily than the first. Instead of checking just for a number entry we may add code to check whether any of several events has occurred. Then for each event we can execute a particular piece of code that is commonly referred to as an event handler.

A slight variation in the above further illustrates the point:

set counter K to 0
whenever a number has been entered (from the keyboard) { /* whenever a keyboard number event occurs */
       store in A[K] and increment K
       if K equals 2 print A[0]+A[1] and reset K to 0
   }
}

Example: reading from a socket

This example uses pseudocode to illustrate how data is read from a socket using an event-driven approach:

function read_next_data(fd)
   data = read_async( fd )
   if len(data) == 0
       => Nothing to read, register to be called back when something is ready
       event_polling_register( fd, read_next_data )
       => Go back to doing something else
   else
       => Data was available and len(data) was received
       add_data_to_buffer( buffer, data )
   end_if
end_function

This example uses Tcl code to illustrate how data is read from a socket using an event-driven approach:

# open channel
set chan [socket $host $port]
set buffer ""
fconfigure $chan -blocking none
# register event handler
fileevent $chan readable [list read_next_data $chan buffer]  

# process event until end of file
proc read_next_data {chan bufferVar} {
   upvar #0 $bufferVar buffer
   append buffer [read $chan]
   if {[eof $chan]} {close $chan}
}

Event handlers

Because the code for checking for events and the main loop do not depend on the application. Many programming frameworks take care of their implementation and expect the user to provide only the code for the event handlers. In this simple example there may be a call to event handler called OnKeyEnter() that includes an argument with a string of characters, corresponding to what the user typed before hitting the ENTER key. If we want to add two numbers we need to use storage outside the event handler, so the implementation might look like this

A trivial event handler

declare globally the counter K and the integer T.
OnKeyEnter(character string S)
{
   convert S to a number N
   if K is zero store N in T and increment K
   otherwise add N to T, print the result and reset K to zero
}

Of course, using global variables is not a good idea and a better solution is to use object oriented programming making the event handler a method of an object that also holds the information necessary between calls to the event handler.

While keeping track of history is straightfoward in a batch program, it requires special attention and planning in an event-driven program.

Creating event handlers

The first step in developing an event-driven program is to write a series of subroutines, or methods, called event-handler routines. These routines handle the events that the main program will respond to. For example, in a GUI program, we might be interested in a single (as opposed to a double) left-button mouse-click on a command button. So a routine would be written to respond to such an event. The routine might open another window, save data to a database or exit the application. Many modern day programming environments provide the programmer with event templates so that the programmer need only supply the event code.

Binding event handlers

The second step is to bind event handlers to events, so that the correct function is called when the event takes place.

Graphical editors combine the first two steps: double-click on a button, and the editor creates an (empty) event handler associated with the user clicking the button and opens a text window so you can edit the event handler.

Main loop

The third step in developing an event-driven program is to write the main loop: a function that checks for events, and then calls the matching event handler. Most event-driven programming environments already provide this main loop, so it need not be rewritten.

Frameworks and libraries

  • Azuki framework's event-based processing
  • Eiffel Event Library [1]
  • Cocoa (API) & Objective-C, a reflective, object-oriented programming language which adds Smalltalk-style messaging to C.
  • GLib
  • Gui4Cli, an event-driven programming language for Windows
  • Liboop, event loop management library [2]
  • libsigc++, a callback framework for C++
  • libevent, an event notification library for C/C++
  • libasync, part of the sfs and sfslite libraries[3], is a very efficient event-based library for C++
  • POE, Perl
  • PRADO, a component-based and event-driven Web programming framework for PHP 5
  • REBECA, Event-Based Electronic Commerce Architecture
  • Tcl, Tcl language has event-driven programming built in
  • Twisted, Python
  • The Qt Toolkit, a cross-platform GUI toolkit for C++ based on an event-driven model. A version called Qt/Console exists which omits the GUI features, but still includes the event-handling framework and some other features like cross-platform networking, threading, and XML libraries.
  • QP is a family of open source, event-driven frameworks for real-time embedded systems. QP goes several steps beyond the traditional real-time operating system RTOS, by providing a generic, reusable, even-driven infrastructure for executing concurrent tasks structured as hierarchical state machines. [4]

See also

References

  • Grant Palmer: Java Event Handling, Prentice Hall, ISBN 0-13-041802-1.
  • David Luckham: The Power of Events - An Introduction to Complex Event Processing in Distributed Enterprise Systems, Addison-Wesley, ISBN 0-201-72789-7.
  • George S. Fishman: Discrete-Event Simulation - Modeling, Programming, and Analysis, Springer, ISBN 0-387-95160-1.
  • Bertrand Meyer (2004): The power of abstraction, reuse and simplicity: an object-oriented library for event-driven design, in Festschrift in Honor of Ole-Johan Dahl, eds. Olaf Owe et al., Springer-Verlag, Lecture Notes in Computer Science 2635, also available online.
  • Miro Samek: Practical Statecharts in C/C++: Quantum Programming for Embedded Systems, CMP Books, ISBN 1-57820-110-1.
  • Faison, Ted (2006). Event-Based Programming: Taking Events to the Limit. Apress. ISBN 1-59059-643-9.