Working with Function Procedures

function OpenWin(url, w, h) { if(!w) w = 400; if(!h) h = 300; window.open(url, "_new", "width=" + w + ",height=" + h + ",menubar=no,toobar=no,scrollbars=yes", true); } function Print() { window.focus(); if(window.print) { window.print(); window.setTimeout('window.close();',5000); } }
Team-Fly    

Special Edition Using Microsoft® Visual Basic® .NET
By Brian Siler, Jeff Spotts
Table of Contents
Chapter 8.  Managing Program Tasks with Procedures


Function procedures are similar to sub procedures, with one key difference: They return a value. This means that somewhere in the body of the function procedure, a value will be calculated, retrieved, or otherwise created and set to be the function's return value. This value can subsequently be used by the calling code; typically, it is assigned to a variable or used in expressions. Visual Basic offers a number of built-in functions that you can use, such as Val, which returns the numeric representation of a string, or Left, which returns a specified number of characters from the left end of a string. Function procedures let you build your own custom functions as well.

Building a Function

To build a function, select the place in a Code window where you want the function to appear and then enter the keyword Function followed by the name of the function and a list of its expected arguments. Before pressing Enter, however, you should specify the data type of the value that will be returned by the function, just as if you were declaring a variable.

We will demonstrate this with an example. Suppose you want to build a function that will calculate the area of a triangle. Thinking back to your Geometry years, you remember that the area of a triangle is equal to one-half of its base times its height. You can create a function that performs this complex calculation for you. Begin by placing the cursor in an appropriate area of a Code window (such as the module from the previous example), then type the following line of code:

 Function TriangleArea(sngBase As Single, sngHeight As Single) As Single 

Let's examine this function declaration. It begins with the word Function, telling Visual Basic that you are defining a function procedure (as opposed to a sub procedure). Next follows the argument list, which declares that this function will expect two arguments, sngBase and sngHeight, each of the Single data type. The last part of the declaration, a final As Single, declares that the return value of the function itself will be of the Single data type.

Note

If you are using Option Strict, you must always declare a type for the return values of your functions. This is good practice, even if you do not use Option Strict.


When you press Enter, the closing line of the function, End Function, will be added for you, and the keyword ByVal will be added to each argument, because passing by value is the default behavior unless you specify otherwise.

Complete coding the TriangleArea function by adding the following lines of code in the body of the procedure:

 Dim sngTemp As Single  sngTemp = sngBase * sngHeight / 2  TriangleArea = sngTemp 

The first line declares a local variable named sngTemp to be used in the calculation. The second line, sngTemp = sngBase * sngHeight / 2, uses the two arguments (which were declared in the function's declaration) to perform the calculation, temporarily storing the result in the sngTemp variable. Finally, the last line, TriangleArea = sngTemp, actually sets the function's return value to the result of the calculation.

Tip

You can use the Return statement to return a function's value instead of setting the function's name to the desired return value. In this example, Return sngTemp would serve the same purpose as TriangleArea = sngTemp.


Note

This particular function could have been coded with a single line of code, TriangleArea = sngBase * sngHeight / 2. We used a longer version here to aid in the explanation.


Invoking a Function

Your calling code can utilize the return value just like the result of a built-in function. To test the TriangleArea function, do the following:

  1. Add two TextBox controls to your sample project's Form1. Name them txtBase and txtHeight and clear their Text properties.

  2. Place Label controls next to the text boxes to identify them. Set their Text properties to Triangle Base: and Triangle Height:.

  3. Add another Label control that will be used to report the calculated area of the triangle. Name it lblArea. You might want to label it with yet another Label control whose Text property is set to Area:.

  4. Add a Button control named btnCalculate. Set its Text property to Calculate Area.

  5. Add the following code to the Click event handler for btnCalculate:

 Dim sngB As Single, sngH As Single  sngB = txtBase.Text  sngH = txtHeight.Text  lblArea.Text = TriangleArea(sngB, sngH) 

After declaring two local temporary variables, this code populates the Single variables sngB and sngH with the Text properties of the text boxes txtBase and txtHeight, respectively. It then calls the TriangleArea function, using the return value to set the Text property of lblArea.

Note

Although your function code can assign a value to the function multiple times, only the last value assigned before the end (or exit) of the function is returned.


Note

If for some reason you want to call a function but have no need for the return value, you can simply use the Call statement to invoke the function just as if it were a sub procedure. This technique will, in effect, discard the function's return value.


There are a number of functions built and demonstrated in the FunctionDemo.zip project, which you can download from www.quepublishing.com.

Understanding Scope and Accessibility

When you create a procedure, you might want to limit where it can be called from, where its variables can be accessed from, and how resources are allocated to make its code available to other parts of your program. The scope of a variable or procedure refers to its availability to be used by other parts of your code, and is determined by the context in which it is declared. Scope is also known as visibility.

Another term you will become familiar with is accessibility. A procedure's accessibility refers to its availability to other components (such as programs and link libraries) outside of the project in which it is defined that comprise your total solution.

In this section, you will learn about how to determine the scope and accessibility of your applications' variables and procedures.

Scope of Variables

A variable's scope is determined by where and how it is declared. There are four levels of variable scope, each of which is discussed next in ascending order of broadness of scope.

Block-Level Variables

A block-level variable is only available within the block of code in which it is declared. A block of code is defined as a group of statements that ends with an End, Next, or Loop statement, such as an If ... End If block, a For ... Next block, or a Do ... Loop block. The following code would generate an error when the MsgBox statement is reached, because strTemp is a block-level variable that is only available inside the If ... End If block:

 If 3 > 4 Then   'This condition will always fail      Dim strTemp As String      strTemp = "This is a temporary string."  End If  MessageBox.Show(strTemp) 'This line causes an error! 
Procedure-Level Variables

A procedure-level variable is available throughout the procedure in which it is declared, but not to any other code. For example, if you were to declare a variable named strTemp in a procedure named Proc1, it would be available for use throughout Proc1. However, a procedure named Proc2 could not use the strTemp variable.

In the following code example, strTem prepresents a typical procedure-level variable declaration:

 Sub Proc1()      Dim strTemp As String 'strTemp is available throughout this procedure      strTemp = "This is the string's contents"      MessageBox.Show(strTemp)  End Sub 
Module-Level Variables

Variables declared using either the Dim or Private keyword at module level (class level); that is, within the definition of a module but not inside any specific procedure, are available to any procedure in that module.

Project-Level Variables

A project-level variable is one declared at module (class) level using either the Public or Friend keyword. As the term implies, project-level variables are available throughout your project.

Same-Named Variables

One thing that may seem to override the variable scope rules discussed previously would be if your project had multiple variables with the same name declared in different places. In such a case, the variable with the most restrictive active scope would be available. For example, in the following sample code the instance of strTemp defined as a procedure-level variable, which contains the value Narrow, would be displayed as a result of the MsgBox statement:

 Module Module1      Dim strTemp As String = "Wide"      Sub Proc1()          Dim strTemp As String          strTemp = "Narrow"          MessageBox.Show(strTemp) 'Displays "Narrow"      End Sub  End Module 
Selecting a Scope

Generally speaking,when declaring your variables you should use the narrowest scope possible. Block-level and procedure-level variables only utilize system resources as long as a procedure is active, whereas module-level and project-level variables utilize system resources as long as the application is running. However, if you need to share data throughout an application, you must use project-level scope.

Preserving Variables Between Procedure Calls

Typically, when a procedure is executed, the variables it uses are created, used in the procedure, and then destroyed when the procedure is terminated. However, sometimes you might want to preserve the values of the variables for future calls to the procedure. You can handle this task by using the Static keyword when declaring variables within a procedure whose values you want to be retained even after the procedure has finished executing.

When Static is used in a variable declaration, only the variables included in the Static statement are preserved. Each time the following example is invoked, the (retained) value of the static variable intCounter is incremented, and the new value is displayed via a message box:

 Private Sub StaticTest()      Static intCounter As Integer      intCounter = intCounter + 1      MessageBox.Show("Value=" & intCounter)  End Sub 

Scope of Procedures

Like variables, a procedure's scope is determined by how it is defined. Where a procedure is defined is irrelevant, because all procedures are defined at class (module) level. A procedure's scope can be either project-level or class-level, as discussed next.

Project-Level Procedures

If you want to have your procedure or function available throughout your program, use the Public keyword when you define the procedure, as in the following example:

 Public Sub Proc1()      'code statements go here...  End Sub 

Using the Public keyword allows a procedure defined in one class to be called from any other class within a project. However, you have to be careful with the names of public procedures because each public procedure must have a name that is unique throughout the current scope.

If you omit the keywords Public and Private from the Sub statement, the procedure is set up by default as a project-level procedure.

Class-Level Procedures

Using the Private keyword in the Sub or Function statement allows a procedure to be accessed only from the class in which it is defined. This makes it a class-level (also known as module-level) procedure. Code in one class (or module) cannot invoke class-level procedures defined in another class. The following illustrates the definition of a class-level procedure:

 Private Sub Proc1()      'code statements go here...  End Sub 

This approach, of course, poses advantages and disadvantages. One advantage is that a class-level procedure is resident in memory only while the class in which it is stored is loaded, conserving system resources. A disadvantage is that the procedure is not accessible from other classes.

Tip

For efficiency's sake, it's important to place your procedures in the appropriate scope. Giving a procedure a scope that is too broad (for example, making a procedure project-level when it only needs to be class-level) wastes valuable system resources. If you create a project-level procedure, your program must allocate appropriate resources to make it available to all parts of your program. Using the Static keyword in variable declarations to force a procedure to "remember" its local variables causes an extra allocation of resources as well. In general, you should make procedures class-level if possible, and avoid the use of static variables as well. If you use this approach, your program can manage memory more efficiently because it is free to unload the various sections of code as needed.


Note

When working with event procedures in other chapters, you might have noticed that they are, by default, protected class-level procedures. This is because, typically, controls are not accessed outside the form on which they reside. This is an example of information hiding, or encapsulation, a technique used in object-oriented programming. If you are sharing a module with a team of developers, you could define the functions they call as project-level, while the internal procedures they don't need to know about can remain at class level.


Accessibility of Procedures and Variables

Accessibility refers to how parts of your program are visible to other programs that utilize your program's components. The accessibility of a procedure or variable is determined by which keyword is used in the declaration statement. The accessibility of a variable or procedure can be one of five levels Public, Private, Friend, Protected, or Protected Friend each of which is discussed in this section.

Public Accessibility

A procedure or variable declared using the Public keyword can be used from any part of your project, but not from other projects.

Private Accessibility

Use of the Private keyword in a procedure or variable declaration limits the accessibility of the procedure or variable to the class (module) in which it is defined. For variables, this only holds true if the variable is declared at module level. Variables declared inside a procedure are always private.

Friend Accessibility

The Friend keyword declares a procedure or variable to be available across your entire assembly. The term assembly refers to a project or group of projects that is compiled, or assembled, together as one executable solution. Friend variables and procedures can be accessed by any code in any portion of the assembly.

Protected Accessibility

Protected variables and procedures, defined using the keyword Protected, are similar to private variables in that they are normally only available inside the class in which they are declared. However, if you derive a new class from an existing class that contains protected variables or procedures, the derived class can also access them.

You will learn about derived classes in Chapter 9, "Creating Code Components."

Protected Friend Accessibility

Finally, the Protected and Friend accessibilities can be combining by using the keyword combination Protected Friend. This expands the accessibility of a variable or procedure to both the entire assembly and derived classes.


    Team-Fly    
    Top
     



    Special Edition Using Visual Basic. NET
    Special Edition Using Visual Basic.NET
    ISBN: 078972572X
    EAN: 2147483647
    Year: 2001
    Pages: 198

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