Home

Introduction to Procedures and Functions

 

Introduction to Procedures

A procedure is a small program that is meant to solve a relatively small problem. In fact, sometimes it is called a sub-program. A program developer writes the procedure and a user (the user is either you or another programmer) would only see the result. There are two categories of procedures you will use in your programs: those that have already been created thus made available to you, and those you will create yourself.

Creating a Procedure

You can create a procedure manually or, if you are using Microsoft Visual Studio, code can be generated for you. To manually create a procedure, start by typing the Sub keyword followed by a name (like everything else, a procedure must have a name). At the end of the procedure, you must type End Sub. Therefore, the primary formula of a procedure is:

Sub ProcedureName()

End Sub

The name of a procedure should follow the rules of names in the Visual Basic language. In addition:

  • If the procedure performs an action that can be represented with a verb, you can use that verb to name it. Here are examples: show, display
  • To make the name of a procedure stand, you should start it in uppercase. Examples are Show, Play, Dispose, Close
  • You should use explicit names that identify the purpose of the procedure. If a procedure would be used as a result of something, reflect it on the name of the sub procedure. Examples would be: afterupdate, longbefore.
  • If the name of a procedure is a combination of words, you should start each word in uppercase. Examples are: AfterUpdate, SayItLoud

To let the studio start a procedure for you, first create a module. In the body of the module, right-click and click Insert Snippet... In the menu, double-click Code Patterns, If, For Each, Property, etc... Double-click Properties, Procedures, Events. Double-click Define a Sub:

	Define a Sub

This would produce:

Module Exercise

    Sub MySub()

    End Sub

End Module

The section between the Sub and the End Sub lines is referred to as the body of the procedure. Here is an example:

Sub Assign()

End Sub

The body of the procedure is used to define what, and how, the assignment should be carried. For example, if you need to use a variable, you can declare it and specify the kind of variable you need. There is no restriction on the type of variables that can be declared in a procedure. Here is an example in which a string variable is declared in the body of a procedure:

Sub Assign()
    Dim strFullName As String
End Sub

In the same way, you can declare as many variables as you need inside of a procedure. The actions you perform inside of a procedure depend on what you are trying to accomplish. For example, a procedure can simply be used to create a string. The above procedure can be changed as follows:

Sub Assign()
    Dim strFullName As String
    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Practical Learning: Introducing Procedures

  1. Start Microsoft Visual Basic
  2. To create a new application, on the main menu, click File -> New Project
  3. In the middle list, click Console Application
  4. In the Name text box, replace the name with Geometry1
  5. Click OK
  6. On the main menu, click Project -> Geormetry1 Properties
  7. Click the arrow of the Application Type box and select Windows Forms Application
  8. Click the Close button Close to close the Property Pages window
  9. In the Solution Explorer, right-click Module1.vb and click Rename
  10. Type Geometry.vb and press Enter
  11. Still in the Solution Explorer, double-click Geometry.vb
  12. To create a procedure, change the document as follows:
    Public Module Geometry
    
        Sub ProcessSquare()
            Dim dblSide As Double
            Dim dblPerimeter As Double
    
            dblSide = InputBox("Enter Side: ")
    
            dblPerimeter = dblSide * 4
    
            MsgBox("=-= Square Characteristics=-=" & vbCrLf &
                   "Side:      " & dblSide & vbCrLf &
                   "Perimeter: " & dblPerimeter)
        End Sub
    
        Sub Main()
    
        End Sub
    
    End Module

Calling a Sub Procedure

Once you have a procedure, whether you created it or it is part of the Visual Basic language, you can use it. Using a procedure is also referred to as calling it. Before calling a procedure, you should first locate the section of code in which you want to use it. To call a simple procedure, type its name followed by parentheses in the section where you want to use it. Here is an example:

Module Exercise

    Sub Assign()
        Dim strFullName As String
        strFullName = "Paul Bertrand Yamaguchi"

        MsgBox(strFullName)
    End Sub

    Friend Sub Main()
        Assign()
    End Sub

End Module

Besides using the name of a procedure to call it, you can also precede it with the Call keyword. Here is an example:

Module Exercise

    Sub Assign()
        Dim strFullName As String
        strFullName = "Paul Bertrand Yamaguchi"

        MsgBox(strFullName)
    End Sub

    Friend Sub Main()
        Call Assign()
    End Sub

End Module

Practical Learning: Calling a Sub Procedure

  1. To call the procedure, type its name in the Main() procedure as follows:
    Module Central
    
        Sub ProcessSquare()
            Dim dblSide As Double
            Dim dblPerimeter As Double
    
            dblSide = InputBox("Enter Side: ")
    
            dblPerimeter = dblSide * 4
    
            MsgBox("=-= Square Characteristics=-=" & vbCrLf &
                   "Side: " & dblSide & vbCrLf &
                   "Perimeter: " & dblPerimeter)
        End Sub
    
        Sub Main()
            ProcessSquare()
        End Sub
    
    End Module
  2. To execute the program, on the Standard toolbar, click the Start Debugging button Start Debugging
  3. Enter the side of the square as 48.14
     
    Square
  4. Click OK to close the message box and return to your programming environment

Procedures and Access Modifiers

Like a variable, a procedure can use access modifiers. A procedure can be made a private procedure, a friendly procedure, or a public procedure, using the Private, the Friend, or the Public keywords respectively:

  • Private: A procedure marked as private can be called only by members of the same module
  • Friend: A friendly procedure can be called by members of the modules of the same application
  • Public: A public procedure can be called from its program and other programs

Practical Learning: Access Modifying a Procedure

  1. To control the access to a procedure, change the file as follows:
    Public Module Geometry
    
        Private Sub ProcessSquare()
            Dim dblSide As Double
            Dim dblPerimeter As Double
    
            dblSide = InputBox("Enter Side: ")
    
            dblPerimeter = dblSide * 4
    
            MsgBox("=-= Square Characteristics =-=" & vbCrLf &
                   "Side: " & dblSide & vbCrLf &
                   "Perimeter: " & dblPerimeter)
        End Sub
    
        Public Sub Main()
            ProcessSquare()
        End Sub
    
    End Module
    
  2. To execute the program, on the main menu, click Debug -> Start Debugging
  3. Enter the side of the square as 105.15
  4. Close the message box and return to your programming environment

Introduction to Functions

 

Introduction

Like a procedure, a function is a sub-program used to perform an assignment. The main difference between a procedure and a function is that, after carrying its assignment, a function gives back a result. We also say that a function "returns a value". To distinguish both, there is a different syntax you use for a function.

Creating a Function

You can manually create a function or, if you are using Microsoft Visual Basic, ask it to create code for you.

To manually create a function, you use the Function keyword followed by a name and parentheses. Unlike a procedure, because a function returns a value, you must specify the type of value the function will produce. To give this information, on the right side of the closing parenthesis, you can type the As keyword, followed by a data type. To indicate where a function stops, type End Function. As seen for a procedure, a function can have an access modifier. The rules for access modifiers are the same as we described for a procedure.

If you are using Microsoft Visual Basic and you want the studio to generate code for you, right-click inslde a module and click Insert Snippet... In the menu, double-click Code Patterns, If, For Each, Property, etc... Double-click Properties, Procedures, Events. Double-click Define a Function.

The minimum formula used to create a function is:

AccessModifier(s) Function FunctionName() As DataType
    
End Function

The Function keyword is required. The name of a function follows the same rules and suggestions we reviewed for sub procedures. The As keyword may be required (in the next sections, we will review the alternatives to the As DataType expression).

The DataType indicates the type of value the function will return. If the function will produce a word or a group of words, you can create it as String. The other data types are also valid in the contexts we reviewed them. Here is an example:

Function GetFullName() As String
        
End Function

As done with the variables, you can also use a type character as the return type of a function and omit the As DataType expression. The type character is typed on the right side of the function name and before the opening parenthesis. An example would be GetFullname$(). As with the variables, you must use the appropriate type character for the function:

Character The function must return
$ a String type
% a Byte, Short, Int16, or In32
& an Int64 or a Long
! a Single type
# a Double
@ a Long integer

Here is an example:

Function GetFullName$()

End Function

As mentioned already, the section between the Function and the End Function lines is the body of the function. It is used to describe what the function does. As done on a sub procedure, one of the actions you can perform in a function is to declare a (local) variable and use it as you see fit. Here is an example:

Function CallMe() As String
    Dim Salute As String
    Salute = "You can call me Al"
End Function

Returning a Value From a Function

After performing an assignment in a function, to indicate the value it returns, somewhere after the assignment and before the End Function line, you can type the name of the function, followed by the = sign, followed by the value the function returns. Here is an example in which a function returns a name:

Function GetFullName$()
        Dim FirstName As String, LastName As String

        FirstName = InputBox("Enter First Name: ")
        LastName = InputBox("Enter Last Name: ")

        GetFullName = LastName & ", " & FirstName
End Function

Alternatively, instead of using the name of the function to indicate the value it returns, you can type Return, followed by the value or the expression that the function returns. Based on this, the above function could also be created as follows:

Function GetFullName$()
    Dim FirstName As String, LastName As String

    FirstName = InputBox("Enter First Name: ")
    LastName = InputBox("Enter Last Name: ")

    Return LastName & ", " & FirstName
End Function

You can also use some local variables in the function to perform an assignment and then assign their result to the name of the function.

Author Note

New Convention:

From now on, in our lessons, to refer to a procedure or function, we will use the name of a procedure followed by parentheses. For example, we may write "the Convert() procedure" or "the Convert() function".

Practical Learning: Creating a Function

  • To create a function, change the file as follows:
    Module Geometry
    
        Private Sub ProcessSquare()
            Dim dblSide As Double
            Dim dblPerimeter As Double
    
            dblSide = InputBox("Enter Side: ")
    
            dblPerimeter = dblSide * 4
    
            MsgBox("=-= Square Characteristics=-=" & vbCrLf &
                   "Side:      " & dblSide & vbCrLf &
                   "Perimeter: " & dblPerimeter)
        End Sub
    
        Private Function CalculatePerimeter() As Double
            Dim dblLength As Double
            Dim dblWidth As Double
    
            dblLength = InputBox("Enter Rectangle Length: ")
            dblWidth = InputBox("Enter Rectangle Width:  ")
    
            CalculatePerimeter = (dblLength + dblWidth) * 2
        End Function
    
        Public Sub Main()
    
        End Sub
    
    End Module

Calling a Function

As done for the sub procedure, in order to use a function in your program, you must call it. Like a sub procedure, to call a function, you can simply type its name in the desired section of the program. Here is an example:

Sub Main()
    CallMe
End Sub

Since the primary purpose of a function is to return a value, to better take advantage of such a value, you can assign the name of a function to a variable in the section where you are calling the function. Here is an example:

Module Exercise

    Function GetFullName$()
        Dim FirstName As String, LastName As String

        FirstName = InputBox("Enter First Name: ")
        LastName = InputBox("Enter Last Name: ")

        Return LastName & ", " & FirstName
    End Function

    Friend Sub Main()
        Dim FullName$

        FullName = GetFullName()
        MsgBox(FullName)
    End Sub

End Module

Here is an example of running this program:

Function

Function

Function

Practical Learning: Calling a Function

  1. To call a function, change the file as follows:
    Public Module Rectangle
    
        Private Function CalculatePerimeter() As Double
            Dim dblLength As Double
            Dim dblWidth As Double
    
            dblLength = InputBox("Enter Rectangle Length: ")
            dblWidth = InputBox("Enter Rectangle Width:  ")
    
            CalculatePerimeter = (dblLength + dblWidth) * 2
        End Function
    
        Public Sub Main()
            Dim Perimeter As Double
    
            Perimeter = CalculatePerimeter()
    
            MsgBox("=-= Square Characteristics=-=" & vbCrLf &
                   "Perimeter: " & Perimeter)
        End Sub
    
    End Module
  2. To execute the program, on the Standard toolbar, click the Start Debugging button Start Debugging
  3. Enter the length as 25.52 and the width as 20.84
  4. Close the message box to return to your programming environment

The Main() Procedure

The Visual Basic Language uses a special procedure and function called Main. Main is the entry point of a program as we have used it so far. Particularly, Main can be used as a procedure or a function. So far, we have used Main only as a procedure. To use Main as a function, type the Function keyword required for each function, followed by Main(), followed by As Integer. When declared like this, the Main function must return an integer. The most regularly return value is 0, which indicates that the function ended successfully. Here is an example:

Module Exercise

    Friend Function GetFullName$()
        Dim FirstName As String, LastName As String

        FirstName = InputBox("Enter First Name: ")
        LastName = InputBox("Enter Last Name: ")

        Return LastName & ", " & FirstName
    End Function

    Friend Function Main() As Integer
        Dim FullName$

        FullName = GetFullName()
        MsgBox(FullName)

        Return 0
    End Function

End Module

Practical Learning: Using the Main Function

  1. To use Main() as a function, change it as follows:
    Module Geometry
    
        Private Sub ProcessSquare()
            Dim dblSide As Double
            Dim dblPerimeter As Double
    
            dblSide = InputBox("Enter Side: ")
    
            dblPerimeter = dblSide * 4
    
            MsgBox("=-= Square Characteristics=-=" & vbCrLf &
                   "Side:      " & dblSide & vbCrLf &
                   "Perimeter: " & dblPerimeter)
        End Sub
    
        Private Function CalculatePerimeter() As Double
            Dim dblLength As Double
            Dim dblWidth As Double
    
            dblLength = InputBox("Enter Rectangle Length: ")
            dblWidth = InputBox("Enter Rectangle Width:  ")
    
            CalculatePerimeter = (dblLength + dblWidth) * 2
        End Function
    
        Public Function Main() As Integer
            Dim Perimeter As Double
    
            Perimeter = CalculatePerimeter()
    
            MsgBox("=-= Square Characteristics=-=" & vbCrLf &
                   "Perimeter: " & Perimeter)
    
            Return 0
        End Function
    
    End Module
  2. To execute the program, on the Standard toolbar, click the Start Debugging button Start Debugging
  3. Enter the length as 88.16 and the width as 44.14
  4. Close the message box and return to your programming environment

Maintenance of Procedures

 

Introduction

Depending on an author, in the Visual Basic language, the word "procedure" includes either a procedure created with the Sub keyword, or a function created with the Function keyword. In the same way, for the rest of our lessons, the word procedure will be used to represent both types. Only when we want to be precise will we use the expression "a procedure" or "a sub-procedure" to explicitly mean the type of procedure that does not return a value. When the word "function" is used in our lessons, it explicitly refers to the type of procedure that returns a value.

Accessing a Procedure

If you are using a text editor to write your code, you can use the Edit main menu to do a search on the name of the procedure. If you are using Microsoft Visual Basic, in the top section of the Class View, click the name of the module in which the procedure exists. In the bottom section of the Class View, double-click the name of the procedure. The Code Editor would jump to where the procedure was defined. As an alternative, if you see a section where the procedure gets called in the Code Editor, right-click its name and click Go To Definition. This would select the name of the procedure where it is defined.

Renaming a Procedure

You can rename a procedure the same you would proceed for a variable. If you are using a text editor like Notepad, you can do a search on its name and replace all instances with a new name. If you are using Microsoft Visual Basic, Find the name of the procedure where it is defined and change it:

Rename

Then click the button under the new name, click the arrow on the button and click Rename.

 
 

Home Copyright © 2008-2016, FunctionX, Inc. Next