CREATING PROCEDURES


In the previous chapter's project, the Dice Poker game, you were required to create two custom procedures in which you added code to manage the process of rolling the game's virtual die and totaling the game score. By creating these two procedures and assigning the code statements that performed specific tasks, you were able to simplify the logic in the Click procedure for the btnRollDice control. This made the overall development of the game a lot easier. As your applications continue to grow in size and complexity, it will become increasingly difficult to write them without using custom procedures.

Procedures make application development easier by providing you with the ability to break applications down into small pieces, which work together. This allows you to group related statements and to focus on writing your application one procedure at a time.

image from book
DEFINITION

A procedure is a collection of program statements that are called and executed as a unit.

image from book

Because a procedure can be called and executed over and over again as needed, procedures also facilitate code reduction, which in turn makes your applications easier to develop and maintain. For example, anytime that you find yourself adding code to perform the same set of steps over again at various points in your applications, it's a good idea to create a single procedure that performs the task and then to call upon that procedure as needed.

image from book
IN THE REAL WORLD

In most cases, professional programmers try to develop procedures that perform one specific task. This streamlines application code and makes it modular. It also helps to reduce errors. For example, suppose you wrote a procedure that performed three or four separate tasks and then later decided that you needed to modify the code for one of the tasks. Because all the programming logic for all three or four tasks is grouped together, you significantly increase the chances that when you go to make a change to the code for one task, you might accidentally modify the code for the logic that performs a different task. Therefore, by putting the code for a specific task into its own procedure, you isolate its code from that stored in other procedures. This also has the added benefit of streamlining the code in each procedure, because no extraneous code unnecessary to performing its specific task is kept inside the procedure.

image from book

Sub and Function Procedures

Procedures begin with a declaration statement (Sub or Function) and end with an End statement. When called, program flow is transferred from the statement that calls the procedure to the procedure itself. Once the procedure finishes executing, program flow is returned back to the calling statement, as demonstrated in Figure 8.8.

Procedures make for better organization of application logic by allowing you to group logical tasks together and to isolate those tasks from other tasks. Procedures also facilitate the development of smaller applications by providing a means of creating reusable tasks that you can call as many times as necessary. On top of all this, procedures help make code maintenance a lot easier by allowing you to isolate and streamline your code. For example, you will find it a lot easier to make a change to a single procedure that performs a commonly called up task than it would be to make the same change over and over again to code that otherwise might be replicated at various points within an application.

image from book
Figure 8.8: A procedure returns program flow control back to the statement that calls it once it finishes executing.

Visual Basic allows you to organize your application into two primary types of procedures, as outlined below.

  • Sub. A type of procedure that executes a set of embedded statements but does not return a value to the statement that called it

  • Function. A type of procedure that executes a set of embedded statements and can optionally return a value to the statement that called it

Handling Events

With the exception of declaration statements, all Visual Basic code has to be stored inside a procedure. As I have already stated, you have been working with procedures in all of the chapter projects that you have completed so far in this book. For example, in many of the chapter game projects, you have added code to perform tasks that executed when the application was first loaded. Before adding this code, you double-clicked on the game project's form when viewing it in the form designer in order to get Visual Basic to automatically generate a Load event procedure for you, which was then displayed in the code editor. A good example of this can be taken from the Dice Poker game's form Load event procedure, which is shown below.

 Private Sub Form1 Load(ByVal sender As System.Object, _   ByVal e As System.EventArgs) Handles MyBase.Load      pbxDie1.Image = imlDiceList.Images(5)      pbxDie2.Image = imlDiceList.Images(5)      pbxDie3.Image = imlDiceList.Images(5)      pbxDie4.Image = imlDiceList.Images(5)      pbxDie5.Image = imlDiceList.Images(5)      txtOutput.Text = ControlChars.CrLf & "Welcome! Are you ready " & _        "to play Dice Poker?" & ControlChars.CrLf & ControlChars.CrLf & _        "You have " & intTotalDollars & " dollars in your account." End Sub 

If you go back and look at the rest of the code in the Dice Poker game, you'll see that it is all organized inside various procedures, most of which were generated automatically for you by Visual Basic.

Sub Procedures

Each procedure, whether it is a Sub or a Function procedure, must be assigned a unique name when it is declared. A Sub procedure is declared using the Sub and End Sub statements. Sub procedures are designed to group related statements together, which can then be executed as a unit. Sub procedures execute without returning any results back to the statement that calls them. Once its execution is completed, a Sub procedure returns processing control back to its calling statement.

The syntax that you'll use when defining your own custom Sub procedure is outlined below.

 [Public | Private | Friend] Sub name [(arglist)]   statements End Sub 

Private is an optional keyword that, when specified, limits access to the procedure to the class or module where it is declared. Public is an optional keyword that, when specified, makes the procedure available without restriction. Friend is an optional keyword that, when specified, makes the procedure available throughout an entire application. Name represents the name that you will assign to the Sub procedure. Arglist is a list made up of one or more comma-separated arguments that can be passed to the Sub procedure for processing. Statements represent one or more code statements that you insert inside the Sub procedure.

Trap 

Just like a variable name, a Sub procedure's name must be unique within its defined scope, otherwise an error will occur.

Defining a Custom Sub Procedure

Let's take a look at an example of a small Sub procedure named GoodBye().

 Public Sub GoodBye()      MessageBox.Show("Please play again soon.", "Good_Bye Demo") End Sub 

Because the Public keyword was added to the beginning of the Sub procedure declaration, the procedure is accessible from anywhere within the application. When called, the Sub procedure displays a message in a pop-up window and then returns control back to the statement that called it.

Trap 

If you declare a procedure without specifying the Public, Private or Friend keyword. Visual Basic automatically makes the procedure Public. Doing so is considered poor programming practice so be sure to always use the appropriate keyword when defining your own custom procedures.

Calling a Custom Sub Procedure

To execute a Sub procedure, you type the name of the procedure followed by a pair of parentheses. For example, the following statement can be used to call the GoodBye() Sub procedure defined above.

 GoodBye() 

Trick 

You can also call on or execute a procedure using the Call keyword as demonstrated below.

 Call GoodBye() 

However, the Call keyword is considered to be a legacy statement, meaning that it is no longer required and seldom used anymore.

Trick 

You can force the early termination of a Sub procedure using the following statement.

 Exit Sub 

Function Procedures

A Function procedure is declared using the Function and End Function statements. Function procedures work almost exactly like Sub procedures. Function procedures incorporate all the capabilities of Sub procedures. In addition, Function procedures are capable of returning a result (a value) back to their calling statement.

The syntax that you'll use when creating a custom Function procedure is outlined below.

 [Public | Private | Friend] Function name [(arglist)] As DataType   statements   [Return] End Function 

Private is an optional keyword that, when specified, limits access to the procedure to the class or module where it is declared. Public is an optional keyword that, when specified, makes the procedure available without restriction. Friend is an optional keyword that, when specified, makes the procedure available throughout an entire application. Name represents the name that you will assign to the Function procedure. Arglist is a list made up of one or more comma-separated arguments that can be passed to the Function procedure for processing. Statements represent one or more code statements that you insert inside the Sub procedure. DataType specifies the data type of the value that the Function procedure will return to its calling statement. Return is a keyword used to specify a value that the Function is to pass back to the statement that called it.

The following example shows a Function procedure that displays a text message in a popup window without returning a result.

 Public Function GoodBye() As String      MessageBox.Show("Please play again soon.", "GoodBye Demo") End Function 

In this example, the Function procedure works exactly like the Sub procedure example you saw earlier. You can execute this procedure from anywhere in your application using the following statement.

 GoodBye() 

Function procedures can also return a result to their calling statements. This can be accomplished in two different ways. The first way is to create a variable with the same name as the Function procedure and to assign it the value that is to be returned, as demonstrated below.

 Public Function GetUserName() As String         GetUserName = InputBox("Please enter your first and last " & _            "name.", "User Name") End Function 

You can call this Function procedure using the statements shown below.

 Dim strUserName As String strUserName = GetUserName() 

In this example, the value returned by the Function procedure is assigned to a variable named strUserName.

Trick 

If you have ever heard the expression "There is more than one way to skin a cat" and are used to working with Microsoft operating systems and applications, then you are probably used to being able to do things in several different ways. Retrieving data from procedures is no different. Instead of setting up your Function procedures so that they can return a value, you have the option of defining module or class-level variables, which you can then modify from within your Sub and Function procedures. This negates the need to return a value in order to make that value available to another part of the application. However, all things being equal, it is better to return a value using a Function procedure and to leave your variables scoped as tightly as possible.

Note that in this example the value stored in the strUserName variable is not returned until the function finishes executing.

Trick 

You can force the early termination of a Function procedure using the following statement.

 Exit Function 

The Exit Function statement forces an immediate exit of the function and returns a value, if one has been specified.

The second way to set up a function to return a value is to use the Return statement to specify the value that you want returned, as demonstrated below.

 Public Function GetUserName() As String      Dim strUserName      strUserName = InputBox("Please enter your first and last " &_        "name.", "User Name")      Return strUserName End Function 

Using the Return statement is the preferred method for returning a value back to a calling statement. It makes your code easier to read and I strongly recommend that you always use it.

Trap 

If a Function procedure ends without setting a return value, Visual Basic will automatically supply a default value. For example, a 0 will be returned for a function with one of the numeric data types, and an empty string (" ") will be returned for function with a String data type. Unless you want your functions to return default values, you need to be sure that you set them up to return the appropriate value. Otherwise, if no return value is required, change your Function procedure to a Sub procedure.

You can also call on functions by referring to them as part of another statement, as demonstrated in the following example.

 MessageBox.Show("Hello " & GetUserName()) 




Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
ISBN: 1592008143
EAN: 2147483647
Year: 2006
Pages: 126

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net