event-driven programming
   HOME

TheInfoList



OR:

In
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as anal ...
, event-driven programming is a programming paradigm in which the flow of the program is determined by
event Event may refer to: Gatherings of people * Ceremony, an event of ritual significance, performed on a special occasion * Convention (meeting), a gathering of individuals engaged in some common interest * Event management, the organization of e ...
s such as user actions ( mouse clicks, key presses), sensor outputs, or
message passing In computer science, message passing is a technique for invoking behavior (i.e., running a program) on a computer. The invoking program sends a message to a process (which may be an actor or object) and relies on that process and its support ...
from other programs or threads. Event-driven programming is the dominant paradigm used in
graphical user interface The GUI ( "UI" by itself is still usually pronounced . or ), graphical user interface, is a form of user interface that allows users to interact with electronic devices through graphical icons and audio indicator such as primary notation, inst ...
s and other applications (e.g., JavaScript
web application A web application (or web app) is application software that is accessed using a web browser. Web applications are delivered on the World Wide Web to users with an active network connection. History In earlier computing models like client-serv ...
s) that are centered on performing certain actions in response to
user input In computing, input/output (I/O, or informally io or IO) is the communication between an information processing system, such as a computer, and the outside world, possibly a human or another information processing system. Information, Inputs are ...
. This is also true of programming for device drivers (e.g., P in USB device driver stacks). In an event-driven application, there is generally a
main loop In computer science, the event loop is a programming construct or design pattern that waits for and dispatches events or messages in a program. The event loop works by making a request to some internal or external "event provider" (that generally ...
that listens for events and then triggers a
callback function In computer programming, a callback or callback function is any reference to executable code that is passed as an argument to another piece of code; that code is expected to ''call back'' (execute) the callback function as part of its job. Thi ...
when one of those events is detected. In
embedded system An embedded system is a computer system—a combination of a computer processor, computer memory, and input/output peripheral devices—that has a dedicated function within a larger mechanical or electronic system. It is ''embedded'' ...
s, the same may be achieved using
hardware interrupt In digital computers, an interrupt (sometimes referred to as a trap) is a request for the processor to ''interrupt'' currently executing code (when permitted), so that the event can be processed in a timely manner. If the request is accepted, ...
s instead of a constantly running main loop. Event-driven programs can be written in any
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
, although the task is easier in languages that provide high-level abstractions, such as
await In computer programming, the async/await pattern is a syntactic feature of many programming languages that allows an asynchronous, non-blocking function to be structured in a way similar to an ordinary synchronous function. It is semantically rel ...
and closures.


Event handlers


A trivial event handler

Because the code for checking of events and the
main loop In computer science, the event loop is a programming construct or design pattern that waits for and dispatches events or messages in a program. The event loop works by making a request to some internal or external "event provider" (that generally ...
are common amongst applications, 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 an event handler called that includes an argument with a string of characters, corresponding to what the user typed before hitting the ENTER key. To add two numbers, storage outside the event handler must be used. The implementation might look like below. # Globally declare the counter K and the integer T integer K = 0; integer T = 0; function OnKeyEnter(character C) While keeping track of history is normally trivial in a sequential program because event handlers execute in response to external events, correctly structuring the handlers to work when called in any order can require 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 In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed. Functions may ...
, or
methods Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
, called event-handler routines. These routines handle the events to which the main program will respond. For example, a single left-button mouse-click on a command button in a
GUI The GUI ( "UI" by itself is still usually pronounced . or ), graphical user interface, is a form of user interface that allows users to interact with electronic devices through graphical icons and audio indicator such as primary notation, inste ...
program may trigger a routine that will open another window, save data to a
database In computing, a database is an organized collection of data stored and accessed electronically. Small databases can be stored on a file system, while large databases are hosted on computer clusters or cloud storage. The design of databases s ...
or exit the application. Many modern-day programming environments provide the programmer with event templates, allowing the programmer to focus on writing the event code. 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. The third step in developing an event-driven program is to write the
main loop In computer science, the event loop is a programming construct or design pattern that waits for and dispatches events or messages in a program. The event loop works by making a request to some internal or external "event provider" (that generally ...
. This is a function that checks for the occurrence of events, and then calls the matching event handler to process it. Most event-driven programming environments already provide this main loop, so it need not be specifically provided by the application programmer. RPG, an early programming language from IBM, whose 1960s design concept was similar to event-driven programming discussed above, provided a built-in main I/O loop (known as the "program cycle") where the calculations responded in accordance to 'indicators' (
flags A flag is a piece of textile, fabric (most often rectangular or quadrilateral) with a distinctive design and colours. It is used as a symbol, a signalling device, or for decoration. The term ''flag'' is also used to refer to the graphic desi ...
) that were set earlier in the cycle.


Exception handlers in PL/I

In
PL/I PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language developed and published by IBM. It is designed for scientific, engineering, business and system programming. I ...
, even though a program itself may not be predominantly event-driven, certain abnormal events such as a hardware error, overflow or "program checks" may occur that possibly prevent further processing. Exception handlers may be provided by "ON statements" in (unseen) callers to provide
cleaning Cleaning is the process of removing unwanted substances, such as dirt, infectious agents, and other impurities, from an object or environment. Cleaning is often performed for aesthetic, hygienic, functional, environmental, or safety purposes ...
routines to clean up afterwards before termination, or to perform recovery operations and return to the interrupted procedure.


Common uses

Most existing GUI development tools and architectures rely on event-driven programming. The Java AWT framework processes all UI changes on a single thread, called the
Event dispatching thread The event dispatching thread (EDT) is a background thread used in Java to process events from the Abstract Window Toolkit (AWT) graphical user interface event queue. It is an example of the generic concept of event-driven programming, that is popu ...
. Similarly, all UI updates in the Java framework
JavaFX JavaFX is a software platform for creating and delivering desktop applications, as well as rich web applications that can run across a wide variety of devices. JavaFX has support for desktop computers and web browsers on Microsoft Windows, Linu ...
occur on the JavaFX Application Thread. In addition, systems such as Node.js are also event-driven.


Criticism

The design of those programs which rely on event-action model has been criticised, and it has been suggested that the event-action model leads programmers to create error-prone, difficult to extend and excessively complex application code. Table-driven state machines have been advocated as a viable alternative. On the other hand, table-driven state machines themselves suffer from significant weaknesses including the state explosion phenomenon. A solution for this is to use
Petri nets A Petri net, also known as a place/transition (PT) net, is one of several mathematical modeling languages for the description of distributed systems. It is a class of discrete event dynamic system. A Petri net is a directed bipartite graph that ...
.


Stackless threading

An event-driven approach is used in
hardware description language In computer engineering, a hardware description language (HDL) is a specialized computer language used to describe the structure and behavior of electronic circuits, and most commonly, digital logic circuits. A hardware description language en ...
s. A thread context only needs a CPU stack while actively processing an event; once done, the CPU can move on to process other event-driven threads, which allows an extremely large number of threads to be handled. This is essentially a
finite-state machine A finite-state machine (FSM) or finite-state automaton (FSA, plural: ''automata''), finite automaton, or simply a state machine, is a mathematical model of computation. It is an abstract machine that can be in exactly one of a finite number o ...
approach.


See also

*
Autonomous peripheral operation In computing, autonomous peripheral operation is a hardware feature found in some microcontroller architectures to off-load certain tasks into embedded autonomous peripherals in order to minimize latencies and improve throughput in hard real-tim ...
*
Comparison of programming paradigms This article attempts to set out the various similarities and differences between the various programming paradigms as a summary in both graphical and tabular format with links to the separate discussions concerning these similarities and differ ...
*
Dataflow programming In computer programming, dataflow programming is a programming paradigm that models a program as a directed graph of the data flowing between operations, thus implementing dataflow principles and architecture. Dataflow programming languages share s ...
(a similar concept) * DOM events *
Event-driven architecture Event-driven architecture (EDA) is a software architecture paradigm promoting the production, detection, consumption of, and reaction to events. Overview An ''event'' can be defined as "a significant change in state". For example, when a consumer p ...
*
Event stream processing In computer science, stream processing (also known as event stream processing, data stream processing, or distributed stream processing) is a programming paradigm which views data streams, or sequences of events in time, as the central input and o ...
(a similar concept) *
Hardware description language In computer engineering, a hardware description language (HDL) is a specialized computer language used to describe the structure and behavior of electronic circuits, and most commonly, digital logic circuits. A hardware description language en ...
*
Interrupt In digital computers, an interrupt (sometimes referred to as a trap) is a request for the processor to ''interrupt'' currently executing code (when permitted), so that the event can be processed in a timely manner. If the request is accepted, ...
*
Inversion of control In software engineering, inversion of control (IoC) is a design pattern in which custom-written portions of a computer program receive the flow of control from a generic framework. A software architecture with this design inverts control as co ...
*
Message-oriented middleware Message-oriented middleware (MOM) is software or hardware infrastructure supporting sending and receiving messages between distributed systems. MOM allows application modules to be distributed over heterogeneous platforms and reduces the comple ...
*
Programming paradigm Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. Some paradigms are concerned mainly with implications for the execution model of the language, suc ...
*
Publish–subscribe pattern In software architecture, publish–subscribe is a messaging pattern where senders of messages, called publishers, do not program the messages to be sent directly to specific receivers, called subscribers, but instead categorize published mes ...
*
Reactor pattern The reactor design pattern is an event handling pattern for handling service requests delivered concurrently to a service handler by one or more inputs. The service handler then demultiplexes the incoming requests and dispatches them synchronou ...
* Signal programming (a similar concept) *
Staged event-driven architecture The staged event-driven architecture (SEDA) refers to an approach to software architecture that decomposes a complex, event-driven application into a set of stages connected by queues. It avoids the high overhead associated with thread-based concu ...
(SEDA) *
Time-triggered system Time-triggered architecture (abbreviated as TTA), also known as a time-triggered system, is a computer system that executes one or more sets of tasks according to a pre-determined and set task schedule.Pont, M.J. (2001) "Patterns for Time-Triggered ...
(an alternative architecture for computer systems) *
Virtual synchrony A reliable multicast is any computer networking protocol that provides a ''Reliability (computer networking), reliable'' sequence of packets to multiple recipients simultaneously, making it suitable for applications such as multi-receiver file tran ...
, a distributed execution model for event-driven programming


References


External links


Concurrency patterns presentation
given a
scaleconfEvent-Driven Programming: Introduction, Tutorial, History
tutorial by Stephen Ferg

tutorial by Alan Gauld

article by Martin Fowler

article by Jonathan Simon

, article by Chris McDonald
Event Driven Programming using Template Specialization
article by Christopher Diggins *
Event-Driven Programming and Agents
chapter
LabWindows/CVI ResourcesDistributed Publish/Subscribe Event System
an open-source example which is in production on MSN.com and Microsoft.com
Javascript Event loop
{{DEFAULTSORT:Event-Driven Programming Programming paradigms Events (computing) Articles with example pseudocode