Procedures        

 

The best way to develop and maintain a large program is to construct it from smaller pieces, which are more manageable than the original program, i.e., divide and conquer.

Programmer-defined procedures define specific tasks that may be used at many points in a program. The statements that make up the procedure are written only once and these statements are not visible to other procedures.


There are several motivations for modularizing a program into procedures:

  • The divide-and-conquer approach makes program development more manageable.
  • Modularization allows software reusability---using existing procedures as building blocks to create new programs. With good procedure naming and definition, programs can be created from standardized procedures, rather than being built by writing customized code.
  • Modular design also makes it possible to avoid repeating code in a program. Packaging code as a procedure allows that code to be executed from several locations in a program simply by calling the procedure.

Modules A project is made up of modules--such as form modules.

  • Projects can contain multiple forms
  • Each form is stored in a form module
  • A form module contains code to create control instances, as well as code written by the developer to perform tasks
  • File suffix is .vb (do not change file suffix or VB .NET will not be able to locate files)
Form modules consist of smaller pieces called procedures.
  • When procedures are part of a class, like click event of the textbox class, they are referred to as methods. 
  • Programmers can create their own procedures (called Sub procedures and Function procedures) to meet the unique requirements of the problems they solve.  

A procedure is invoked by a procedure call, which specifies the procedure name and provides information (as arguments) that the called procedure needs to do its job. 

Procedures allow the programmer to modularize a program.

A common analogy for this is the hierarchical form of management. A boss (the caller) asks a worker (the procedure) to perform a task and return (i e., report back) the results when the task is done. The boss does not know how the worker performs its designated tasks. The worker may call other workers--the boss will be unaware of this


Sub Procedures

You've seen examples of subs prior to this.  For example, when we were exploring error checking the notes provided a sub procedure designed to allow the user to correct invalid input more easily.  The sub accepts as an argument the name of the textbox in which the invalid input was entered, and then returns program focus to that textbox, highlighting the invalid entry in the text box so that the user does not have to erase the existing entry before entering the correct value.

'-----------------------------------------------------------------------
' This sub accepts a text box as a parameter, sets the focus to that box,
' places the cursor at the beginning of the box, and highlights the text.
'-----------------------------------------------------------------------
Private Sub textHighlighter(ByVal txtVar As TextBox)
     txtVar.Focus
     txtVar.SelectionStart = 0                            ' Set cursor to beginning of box
     txtVar.SelectionLength = Len(txtVar.Text) ' Highlight text
End Sub

Each time that the user is required to re-enter data, this sub can be called by passing the text box name as a parameter, such as Call textHighlighter(txtTempF).


Sub Procedure Definition

The code representing the procedure is called the Sub procedure definition.

Private Sub textHighlighter (ByVal txtVar As TextBox)
 
End Sub

________________

Sub Procedure Header

Private Sub sub_name ( ByVal/ByRef parameter list) 

example: Private Sub textHighlighter (ByVal txtVar As TextBox)

   or more detailed

Private Sub sub_name ( ByVal/ByRef param1 as type, 
   ByVal/ByRef param2 as type, ...., ByVal/ByRef paramn as type) 

  • The Sub procedure header contains keyword Private, keyword Sub, the procedure name, and parentheses.
  • All Sub procedure definitions contain parentheses which may be empty or may contain a list of variable declarations (called a parameter list).
  • Parameter variables are declared using the As keyword.
  • Parameter variables receive their values from the procedure call and are used in the procedure body.

Private Sub AnotherProcedure( )

________________

Sub Procedure Body

Any declarations and statements the programmer places between the header and End Sub form the Sub-procedure body.

Every time the Sub procedure is called (or invoked) the body is immediately executed.

Execution of the Sub procedure terminates when End Sub is reached and program execution then continues with the statement immediately following the call.

Private Sub ShowPay(ByVal hours As Single, ByVal wage As Double)
      Console.WriteLine (hours * wage)
End Sub

________________

Procedure Calls

A procedure call uses keyword Call and encloses the arguments passed in a set of parentheses.

Procedure ShowPay is called with the line

Call Showpay(40.0, 10.00)

which passes into ShowPay values for parameter hours (40) and parameter wage (10.00).

The arguments passed can be variable names as well:

Call ShowPay (empHours, empWage)

Procedure arguments, both for subs and functions, are matched up based on the number, position, and type in the argument list.  This is often referred to as the procedure's signature, or external interface.

________________

Note also that procedures can also be invoked without the statement, but that is not the preferred approach.


Function Procedures

Unlike Sub procedures, which do not return a value, Function procedures return a value to the calling routine.

________________

Function Procedure Header

Private Function function_name ( ByVal parameter list) As return_type

   or more detailed

Private Function function_name ( ByVal param1 As type, ByVal
   param2 As type, ...., ByVal paramn As type) As return_type

  • The Function procedure header contains keyword Private, keyword Function, the function name, and parentheses.
  • All Function procedure definitions contain parentheses, which may be empty or may contain one or parameter variable declarations.
  • Parameter variables are declared using the As keyword.
  • Parameter variables receive their values from the function call and are used in the function body.
  • Return types should be explicitly stated in the Function procedure header using the As keyword.
           
    Private Function getArea (ByVal sl As Single, ByVal s2 As Single) As Single
            Private Function isVolunteer08 ( ) As Boolean

________________

Example

The example below is a modification of the day of week program discussed earlier.  This example uses a programmer-defined Function procedure dayOfWeek to determine the corresponding week day name of a particular date.  Note that the dayOfWeek function calls two built-in VB functions.  The result is returned through the function name.

Private Function dayOfWeek(ByVal dateEntered As Date) As String
     Return WeekdayName(Weekday(dateEntered))
End Function

Private Sub cmdCalc_Click(ByVal sender As System.Object, _
   ByVal
e As System.EventArgs) Handles cmdCalc.Click
     txtDay.Text = dayOfWeek(DateTime.Now)
    ' or txtDay.Text = dayOfWeek(
CDate(txtDate.Text))
End Sub

________________

Function Procedure Body

Any declarations and statements the programmer places between the header and End Function form the Function procedure body.

Every time the Function procedure is called (or invoked) the body is immediately executed.

________________

Returning Values from Functions

  • A function is designed to return a single value to the calling program through the function name by placing the data type after the keyword As at the end of the function header
  • If a return type is not specified in the declaration, the compiler will assume that the return type is Object.
  • The return value is returned to the calling program through the Function procedure name by using the Return statement, as in Return kilograms

Private Function lbsToKgs (ByVal pounds As Single) As Single
     Dim kilograms As Single
     Const conversionFactor As Single = 0.453592
     kilograms = conversionFactor * pounds
     Return kilograms
End Function

Private Sub cmdWeight_Click(ByVal sender As System.Object, _
   ByVal
e As System.EventArgs) Handles cmdWeight.Click
     Dim kgs As Single
     kgs = lbsToKgs (225)
     Console.WriteLine("Your weight in kilograms is " & kgs)
End Sub

  • When a function returns a value, the call to the function lbs_to_kg(225) is considered to be an expression that takes on the value returned by the function.

Consider the following Function procedure:

Private Function getArea (ByVal s1 As Single, ByVal s2 As Single) As Single
    Return s1 * s2     ' return the area
End Sub

________________

Private Function isVolunteer08(ByVal idNumberValid As Boolean) As Boolean
    If (idNumberValid) then
        Return True
    Else
        Return False
    EndIf
End Function

Note:  Better written as Return idNumberValid

________________

Function Call

When a Function procedure name is encountered at run-time, the Function procedure is called, causing its body statements to execute.

After a Function is executed, control returns (along with the value returned) to the calling statement returnValue = isVolunteer08( )

Program execution then continues with the next statement after the call.

getArea is called with the statement

squareFtNeeded = getArea(8.5, 7.34)

IsVolunteer08 is invoked with the line

futureVolunteer = isVolunteer08 (idNumberOkay )


Be sure not to declare a local variable with the same name as a sub or function.

 


Methods

A method is any procedure that is contained within a class.  You will see more details about methods when we introduce object-oriented programming.