Chapter 20. Reusing Code with Procedures

Sometimes a program needs to perform the same action in several places. For example, suppose you're using a simple editor such as WordPad, you make some changes, and then you select the File menu's New command. The program realizes that you have unsaved changes and asks if you want to save them. Depending on whether you click Yes, No, or Cancel, the program saves the changes, discards the changes, or cancels the attempt to create a new file.

Now consider what happens when you try to open a file while you have unsaved changes. The program goes through basically the same steps, asking if you want to save the changes. It does practically the same thing if you select the File menu's Exit command, or click the X in the program's upper-right corner, or open the window's system menu and select Close, or press [Alt]+F4. In all of these cases, the program performs the same checks.

Instead of repeating code to handle unsaved changes everywhere it might be needed, it would be nice if you could centralize the code in a single location and then invoke that code when you need it. In fact, you can do exactly that by using a procedure.

A procedure is a group of programming statements wrapped in a neat package so you can invoke it as needed. A procedure can take parameters that the calling code can use to give it information, it can perform some actions, and then it can return a single value to pass information back to the calling code.

In this lesson, you learn ...

Get Stephens' Visual Basic® Programming 24-Hour Trainer now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.