Writing Function Procedures


Writing Function Procedures

A Function procedure is a group of statements located between a Function statement and an End Function statement. The statements in the function do the meaningful work—typically processing text, handling input, or calculating a numeric value. You execute, or call, a function in a program by placing the function name in a program statement along with any required arguments.

Arguments are the data used to make functions work, and they must be included between parentheses and be separated by commas. Basically, using a Function procedure is exactly like using a built-in function or method such as Int, Rnd, or FromFile.

TIP
Functions declared in modules are public by default. As a result, you can use them in any event procedure within the project.

Function Syntax

The basic syntax of a function is as follows:

Function FunctionName([arguments]) As Type     function statements     [Return value] End Function

The following syntax items are important:

  • FunctionName is the name of the function you're creating.

  • As Type is a pair of keywords that specifies the function return type. (In Visual Basic 6, a specific type declaration is optional, but it's strongly recommended in Visual Basic 2005. If you don't provide a type, the return type defaults to Object.)

  • arguments is a list of optional arguments (separated by commas) to be used in the function. Each argument should also be declared as a specific type. (By default, Visual Basic adds the ByVal keyword to each argument, indicating that a copy of the data is passed to the function through this argument but that any changes to the arguments won't be returned to the calling routine.)

  • function statements is a block of statements that accomplishes the work of the function. The first statements in a function typically declare local variables that will be used in the function, and the remaining statements perform the work of the function.

  • Return is a newer statement that is not offered in Visual Basic 6—with it, you can indicate when in the function code block you want to return a value to the calling procedure and what that value is. When a Return statement is executed, the function is exited, so if there are any function statements after the Return statement, these won't be executed. (Alternatively, you can use the Visual Basic 6 syntax and return a value to the calling routine by assigning the value to FunctionName.)

  • Brackets ( [] ) enclose optional syntax items. Visual Basic requires those syntax items not enclosed by brackets.

Functions always return a value to the calling procedure in the function's name (FunctionName). For this reason, the last statement in a function is often an assignment statement that places the final calculation of the function in FunctionName. For example, the Function procedure TotalTax computes the state and city taxes for an item and then assigns the result to the TotalTax name, as shown here:

Function TotalTax(ByVal Cost as Single) As Single     Dim StateTax, CityTax As Single     StateTax = Cost * 0.05  'State tax is 5%     CityTax = Cost * 0.015  'City tax is 1.5%     TotalTax = StateTax + CityTax End Function

Alternatively, you can use the Visual Basic 2005 syntax and return a value to the calling procedure by using the Return statement, as shown in the following function declaration:

Function TotalTax(ByVal Cost as Single) As Single     Dim StateTax, CityTax As Single     StateTax = Cost * 0.05  'State tax is 5%     CityTax = Cost * 0.015  'City tax is 1.5%     Return StateTax + CityTax End Function

I'll use the Return syntax most often in this book, but you can use either mechanism for returning data from a function.

Calling a Function Procedure

To call the TotalTax function in an event procedure, you use a statement similar to the following:

lblTaxes.Text = TotalTax(500)

This statement computes the total taxes required for a $500 item and then assigns the result to the Text property of the lblTaxes object. The TotalTax function can also take a variable as an argument, as shown in the following statements:

Dim TotalCost, SalesPrice As Single SalesPrice = 500 TotalCost = SalesPrice + TotalTax(SalesPrice)

The last statement uses the TotalTax function to determine the taxes for the number in the SalesPrice variable and then adds the computed tax to SalesPrice to get the total cost of an item. See how much clearer the code is when a function is used?

Using a Function to Perform a Calculation

In the following exercise, you'll add a function to the Track Wins program to calculate the win rate in the game—in other words, the percentage of spins in which one or more 7s appear. To perform the calculation, you'll add a function named HitRate and a public variable named Spins to the module. Then you'll call the HitRate function every time the Spin button is clicked. You'll display the results in a new label that you'll create on the form.

Create a win rate function

  1. Display the form for the Track Wins program that you've been modifying.

    The user interface for the slot machine game appears.

  2. Use the Label control to create a new label below the Wins label. Set the following properties for the label:

    Object

    Property

    Setting

    Label5

    Font

    ForeColor

    Name

    Text

    TextAlign

    Arial, Bold Italic, 12-point

    Red (on Custom tab)

    lblRate

    “0.0%”

    MiddleCenter

    Your form looks similar to this:

    graphic

  3. In Solution Explorer, click the Module1.vb module, and then click the View Code button.

    The Module1 module appears in the Code Editor.

  4. Type the following public variable declaration below the Public Wins As Short statement:

    Public Spins As Short

    The module now includes two public variables, Wins and Spins, that will be available to all the procedures in the project. You'll use Spins as a counter to keep track of the number of spins you make.

  5. Insert a blank line in the module, and then type the following function declaration:

    Function HitRate(ByVal Hits As Short, ByVal Tries As Short) As String     Dim Percent As Single     Percent = Hits / Tries     Return Format(Percent, "0.0%") End Function

    After you type the first line of the function code, Visual Basic automatically adds an End Function statement. After you type the remainder of the function's code, your screen looks identical to this:

    graphic

    The HitRate function determines the percentage of wins by dividing the Hits argument by the Tries argument and then adjusts the appearance of the result by using the Format function. The HitRate function is declared as a string because the Format function returns a string value. The Hits and the Tries arguments are placeholders for the two short integer variables that will be passed to the function during the function call. The HitRate function is general-purpose enough to be used with any shorter integer numbers or variables, not only with Wins and Spins.

  6. Display the form again, and then double-click the Spin button on the TrackWins form to bring up the Button1_Click event procedure.

  7. Below the fourth line of the event procedure (Label3.Text = CStr(Int(Rnd() * 10))), type the following statement:

    Spins = Spins + 1

    This statement increments the Spins variable each time the user clicks Spin, and new numbers are placed in the spin windows.

  8. Scroll down in the Code Editor, and then, between the End If and the End Sub statements, type the following statement as the last line in the Button1_Click event procedure:

    lblRate.Text = HitRate(Wins, Spins)

    As you type the HitRate function, notice how Visual Studio automatically displays the names and types of the arguments for the HitRate function you just built (a nice touch).

    The purpose of this statement is to call the HitRate function by using the Wins and the Spins variables as arguments. The result returned is a percentage in string format, and this value is assigned to the Text property of the lblRate label on the form after each spin. Now remove the Randomize function from the Form1_Load event procedure, so that while you test the project, your results will follow a familiar pattern.

  9. Scroll down in the Code Editor to the Form1_Load event procedure, and remove or “comment out” (place a comment character before) the Randomize function.

Now, each time that you run this program, the random numbers generated will follow a predictable pattern. This helps you test your code, but when you're finished testing, you'll want to add the function back again so that your results are truly random.

Now you'll run the program.

Run the Track Wins program

  1. Click the Start Debugging button to run the modified Track Wins program.

  2. Click the Spin button 10 times.

    The first five times you click Spin, the win rate stays at 100.0%. You're hitting the jackpot every time. As you continue to click, however, the win rate adjusts to 83.3%, 71.4%, 75.0% (another win), 66.7%, and 60.0% (a total of 6 for 10). After 10 spins, your screen looks like this:

    graphic

    If you continue to spin, you'll notice that the win rate drops to about 28%. The HitRate function shows that you were really pretty lucky when you started spinning, but after a while reality sets in.

  3. When you're finished with the program, click the End button.

    The program stops, and the development environment returns. You can add the Randomize function to the Form1_Load event procedure again to see how the program works with “true” randomness. After about 100 spins (enough iterations for statistical variation to even out a little), you should be close to the 28% win-rate each time that you run the program. If you like numbers, it is an interesting experiment.

  4. Click the Save All button on the Standard toolbar to save your changes.



Microsoft Visual Basic 2005 Step by Step
Microsoft Visual Basic 2005 Step by Step (Step by Step (Microsoft))
ISBN: B003E7EV06
EAN: N/A
Year: 2003
Pages: 168

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