0% found this document useful (0 votes)
58 views8 pages

Sekelani 3

This document provides an overview of event-driven programming. It discusses how event-driven programs have a main loop that checks for and handles events. Common events include user input, alarms, and messages from other programs. The document also describes how event handlers are created to handle specific events and how they are bound to those events. It notes some criticisms of the event-driven approach, including potential thread safety issues and complex code from handling all possible event values.

Uploaded by

Ben Ybr Chabala
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views8 pages

Sekelani 3

This document provides an overview of event-driven programming. It discusses how event-driven programs have a main loop that checks for and handles events. Common events include user input, alarms, and messages from other programs. The document also describes how event handlers are created to handle specific events and how they are bound to those events. It notes some criticisms of the event-driven approach, including potential thread safety issues and complex code from handling all possible event values.

Uploaded by

Ben Ybr Chabala
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Event-driven programming

From Wikipedia, the free encyclopedia Jump to: navigation, search This article has multiple issues. Please help improve it or discuss these issues on the talk page.

Its factual accuracy is disputed. Tagged since October 2009. It may contain original research. Tagged since October 2009.

Programming paradigms

Agent-oriented Automata-based Component-based

Flow-based Pipelined

Concatenative Concurrent computing

Relativistic programming

Data-driven Declarative (contrast: Imperative)

Constraint Dataflow


Logic

Cell-oriented (spreadsheets) Reactive

Abductive logic Answer set Constraint logic Functional logic Inductive logic

Event-driven

Service-oriented Time-driven

Expression-oriented Feature-oriented Function-level (contrast: Value-level) Functional Generic Imperative (contrast: Declarative)

Procedural

Language-oriented

Discipline-specific Domain-specific Grammar-oriented

Dialecting

Intentional

Metaprogramming

Automatic Reflective

Attribute-oriented

Template

Policy-based

Non-structured (contrast: Structured)

Array

Nondeterministic Parallel computing

Process-oriented

Programming in the large / small Semantic

Structured (contrast: Non-structured)

Modular (contrast: Monolithic) Object-oriented

By separation of concerns:

Aspect-oriented Role-oriented Subject-oriented

Class-based Prototype-based

Recursive

Value-level (contrast: Function-level)

v d e

In computer programming, event-driven programming or event-based programming is a programming paradigm in which the flow of the program is determined by eventsi.e., sensor outputs or user actions (mouse clicks, key presses) or messages from other programs or threads. Event-driven programming can also be defined as an application architecture technique in which the application has a main loop which is clearly divided down to two sections: the first is event selection (or event detection), and the second is event handling. In embedded systems the same may be achieved using interrupts instead of a constantly running main loop; in that case the former portion of the architecture resides completely in computer hardware. Event-driven programs can be written in any language, although the task is easier in languages that provide high-level abstractions, such as closures. Some integrated development environments provide code generation assistants that automate the most repetitive tasks required for event handling.

Contents
[hide]

1 Event handlers

1.1 A trivial event handler 1.2 Exception handlers 1.3 Creating event handlers

2 Criticism and best practice 3 Stackless threading 4 See also 5 References 6 External links

[edit] Event handlers


[edit] A trivial event handler
Because the code for checking for events and the main loop does 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 an event handler called OnKeyEnter() 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 so the implementation might look like below.
globally declare the counter K and the integer T. OnKeyEnter(character C) { convert C 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 }

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

[edit] Exception handlers


In some programming languages (e.g., PL/1), 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 prevents further processing. Exception handlers may be provided by "ON statements" in (unseen) callers to provide housekeeping routines to clean up afterwards before termination.

[edit] 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 to which the main program will respond. For example, a single left-button mouse-click on a command button in a GUI program may trigger a routine that will 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 only needs to supply 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. 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) that were set earlier in the cycle.

[edit] Criticism and best practice


Event-driven programming is widely used in graphical user interfaces because it has been adopted by most commercial widget toolkits as the model for interaction. The design of those toolkits has been criticized for promoting an over-simplified model of event-action, leading programmers to create error prone, difficult to extend and excessively complex application code:
[1]

Such an approach is fertile ground for bugs for at least three reasons:
1. It is not thread-safe.

2. It can lead to writing code within the event handler for each possible value of various values in the program, making the source code hard to understand.
3. In places where the event code changes variables shared throughout the program,

it can require the programmer to write convoluted algorithms to avoid unwanted ripple effects.

[edit] Stackless threading


An event driven approach is used in hardware description languages. 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, that allows an extremely large number of threads to be handled. This is essentially a Finite-state machine approach.

Event-Driven Programming
Introduction
Event-driven programming is a flexible way to allow your programs to respond to many different inputs or events. Traditionally, programs operated in a sequential fashion: they did some processing and displayed it, waited for a user response, did some more processing, and so on. Your first OPL program was probably like this:
PROC main: LOCAL name$( 20 ) PRINT "What is your name?" INPUT name$ PRINT "That's a nice name, "; n$; "!" GET ENDP

It prints a prompt, wait for you to enter your name, displays a message with your name in it, then waits for you to press a key to quit the program. This style is easy to understand and program. The problem is when your programs need to become more sophisticated and must deal with more than just you entering information on the keyboard. Perhaps, like me, you watch a bit of TV and you've filled up your Time application with reminders of shows to watch. You need some more alarms. What to do? In OPL you can access the built-in alarm system, and schedule as many alarms as you like. The Agenda does this sort of thing already. What happens is Agenda keeps track of the next alarm and only tells the system about that one. When it goes off, Agenda tells the system about the next alarm, and so on. Agenda can do all this at the same time as letting you type in new entries, search for appointments or print to-do lists. It can do this by waiting for events to occur: A key being pressed An alarm going off RS-232 serial data Digital sound recording and playback System events Touch-screen events (not supported by SIBO machines)

Many other types of events are possible, including, but not limited to:

Event-driven programs improve on sequential programs by having a central event handler and dispatcher that waits for an event (any event) to occur, and then processes that event by calling that event handler.

Separation of the event detection and the event handling is an important technique for keeping your program simple and flexible. It is quite common for applications to have a menu. Each menu item has a hotkey that can be used to do things without going through the menu. Event-driven programs will commonly write a single keyboard event handler that identifies when hotkeys are pressed and called the appropriate function. To handle the situation when the menus are used, they will often translate the menu selection into a keyboard event and let the keyboard handler do all the work! The complete menu handler is often a simple procedure consisting of just a few lines of code! Hopefully I've sold you on the idea of event-driven programming. The next step is: how does it work on the Psion?

Implementation
The key concept to event-driven programming is that your program doesn't just stop and wait for a specific event, like the above example program did, waiting for you to type on your name. You might have looked through the Series 3a Programming Manual and found the KEY command. Initially, the KEY command looks quite useful. It lets you check for a keypress without stopping and waiting for it. That means your application can be busy doing its' thing, and can check the keyboard every now and again to see if you've pressed something. This technique works, but it suffers from a major drawback that particularly impacts on batterypowered handheld computers like your Psion: your program never stops. What this means is your your computer will always be busy, either doing some work, or spinning 'round and 'round, checking if you've pressed a key in the millisecond since it last checked. All this work would quickly run down your batteries. It doesn't seem to bother the built-in programs. How to they do it? The difference is due to the two techniques used to implement event-driven programs: Polling Stop-and-wait (or interrupted)

Polling
Polling is the KEY command: it just polls the keyboard to see if there has been a keypress. The TESTEVENT command is the same. This technique of programming is not at all suitable for the Psion, so it won't be discussed any further.

Stop and Wait


Stop and wait is when your computer stops and waits for something to happen. This allows it to change to a special low-power idle state that is nice to your batteries. The command to use for this technique is GETEVENT. Some typical code using GETEVENT might look like (see the Programming Manual for a full explanation):
PROC mainloop: GLOBAL done% LOCAL a%( 6 ), keycode%, keymod%, keyrep%, syscmd$( 255 ) done% = 0 DO GETEVENT a%() IF ( a%( 1 ) AND $400 ) = 0 REM it's a keypress keycode% = a%( 1 ) keymod% = a%( 2 ) AND $00FF keyrep% = a% ( 2 ) / 256 hdlKey:( keycode%, keymod%, keyrep% ) ELSEIF a%( 1 ) = $401 REM program has come to the foregound ELSEIF a%( 1 ) = $402 REM program has gone

to the background ELSEIF a%( 1 ) = $403 REM machine has switched on ELSEIF a% ( 1 ) = $404 REM system command syscmd$ = GETCMD$ hdlCmd:( LEFT$( syscmd$, 1 ), MID$( syscmd$, 2, 255 ) ) ELSEIF a%( 1 ) = $405 REM date has changed ELSE REM some unknown event (should never happen) ENDIF UNTIL done% ENDP REM Handle keypresses PROC hdlKey:( keycode%, keymod%, keyrep% ) IF keycode% = 27 done% = 1 :REM allow main loop to exit ELSE REM do something with the key PRINT REPT$( CHR$( keycode% ), keyrep% ); ENDIF ENDP REM Handle system command events PROC hdlCmd:( syscmd$, sysfile$ ) IF syscmd$ = "X" done% = 1 :REM allow main loop to exit ENDIF REM there are other "O" open and "C" create commands REM - see the Programming Manual ENDP

This allows your program to handle keyboard events, plus quite a few others. This is sufficient for many applications. However, it does not let you do things like schedule alarms or use the serial port. To do these sorts of things as well requires the use of asynchronous I/O. It is covered in the next tutorial called, funnily enough, Asynchronous I/O.

You might also like