Event Driven vs Procedural Programming

When a traditional procedural application runs, it follows a predetermined path that controls the portions and sequence of code executed. It starts with the first line of code and progresses from the top down, calling each procedure when needed, until reaching the end of the code. This predetermined path is the major difference between procedural and event-driven applications.

Event-driven applications do not have a predetermined destiny. Different sections of code are executed based upon the events triggered in whatever order they occur. Depending on what events occur when the application runs, some sections of code may not get executed at all.

You can't predict the sequence of events, so you must make assumptions about the application's "state" at any moment. This seems like it would be difficult, but it's really not. Typically, you have a set of possibilities to work with, such as the Click, DblClick, KeyPress, and LostFocus events. For example, you might require the user to type a value in a TextBox before enabling a CommandButton that allows further processing. The TextBox control's Change event would contain code that enables the CommandButton control, as shown in this sample code:

Private Sub TextBox1_Change() If Len(TextBox1.Text) > 0 Then CommandButton1.Enabled = True

Else

CommandButton1.Enabled = False End If End Sub

Each time you add or delete text from the TextBox control, the program executes this event procedure. The code checks the length of the text and if it is greater than zero, meaning there is something in the TextBox, it enables the CommandButton. Otherwise, it disables the CommandButton.

Programmatically changing the text in the TextBox triggers the Change event. If you allow for this occurrence, you might get unexpected results. Using events is very powerful, but you must know what each event might trigger elsewhere in your application.

0 0

Post a comment