Title: Chapter 6 Procedures
1Chapter 6-Procedures
2Outline
6.1 Introduction6.2 Modules, Classes and
Procedures6.3 Sub Procedures6.4 Function
Procedures6.5 Methods6.6 Argument
Promotion6.7 Option Strict and Data Type
Conversions6.8 Value Types and Reference
Types6.9 Passing Arguments Pass-by-Value vs.
Pass-by-Reference6.10 Duration of
Identifiers6.11 Scope Rules
36.1 Introduction
- Divide and Conquer
- The best way to develop and maintain a large
program is to construct it from small, manageable
pieces.
46.2 Modules, Classes and Procedures
- Framework Class Library
- Provides a rich collection of prepackaged
classes and methods for performing many
operations - Mathematical calculations
- String manipulations
- Character manipulations
- Input/output operations
- Error checking
56.2 Modules, Classes and Procedures
- Programmer-defined procedures
- FCL cannot provide every conceivable feature that
a programmer could want - Three types of procedures
- Sub procedures
- Function procedures
- Event procedures
- A procedure is invoked by a procedure call
66.3 Sub Procedures
- The programs presented earlier in lectures each
contained at least one procedure definition - (e.g., Main) that called FCL methods (such as
Console.WriteLine) to accomplish the programs
tasks. - We now consider how to write customized
procedures.
7Payment.vbProgram Output
Console application uses a Sub procedure (invoked
from the applications Main procedure) to print a
workers payment information.
- 1 ' Fig. 6.2 Payment.vb
- 2 ' Sub procedure that prints payment
information. - 3
- 4 Module modPayment
- 5
- 6 Sub Main()
- 7
- 8 ' call Sub procedure PrintPay 4 times
- 9 PrintPay(40, 10.5)
- 10 PrintPay(38, 21.75)
- 11 PrintPay(20, 13)
- 12 PrintPay(50, 14)
- 13
- 14 Console.ReadLine() ' prevent window
from closing - 15 End Sub ' Main
- 16
- 17 ' print amount of money earned in command
window - 18 Sub PrintPay(ByVal hours As Double, ByVal
wage As Decimal) - 19
The payment is 420.00 The payment is 826.50 The
payment is 260.00 The payment is 700.00
Notice that PrintPay appears within modPayment.
All procedures must be defined inside a module or
a class
86.3 Sub Procedures
- The program contains two procedure definitions
- Sub procedure Main, which executes when the
console application is loaded. - Sub procedure PrintPay, which executes when it is
invoked, or called, from another procedure, in
this case Main. - Although the procedure arguments in this example
are constants, arguments can also be variables or
expressions. For example, the statement - PrintPay(employeeOneExtraHours,
employeeOneWage 1.5) - could be used to display payment
information for an employee who is being paid
time-and-a-half for working overtime.
96.3 Sub Procedures
- Format of a procedure definition
- Sub procedure-name(parameter-list)
- declarations and statements
- End Sub
- Procedure header
- is he first line.
- ByVal specifies that the calling program should
pass a copy of the value of the argument in the
procedure call to the parameter, which can be
used in the Sub procedure body. - Procedure-name
- Directly follows the Sub keyword
- Can be any valid identifier
- Procedure body
- The declarations and statements in the procedure
definition form the procedure body
10Common Errors
- Declaring a variable in the procedures body with
the same name as a parameter variable in the
procedure header is a syntax error. - Although it is allowable, an argument passed to a
procedure should not have the same name as the
corresponding parameter in the procedure
definition. This distinction prevents ambiguity
that could lead to logic errors. - Defining a procedure inside another procedure is
a syntax errorprocedures cannot be nested. - The procedure header and procedure calls all must
agree with regard to the number, type and order
of parameters.
116.4 Function Procedures
- Similar to Sub procedures
- One important difference
- Function procedures return a value to the caller,
whereas Sub procedures do not.
12Console application uses Function procedure
Square to calculate the squares of the Integers
from 110.
- 1 ' Fig. 6.3 SquareInteger.vb
- 2 ' Function procedure to square a number.
- 3
- 4 Module modSquareInteger
- 5
- 6 Sub Main()
- 7 Dim i As Integer ' counter
- 8
- 9 Console.WriteLine("Number" vbTab
"Square" vbCrLf) - 10
- 11 ' square numbers from 1 to 10
- 12 For i 1 To 10
- 13 Console.WriteLine(i vbTab
Square(i)) - 14 Next
- 15
- 16 End Sub ' Main
- 17
- 18 ' Function Square is executed
- 19 ' only when the function is explicitly
called.
The For structure displays the results of
squaring the Integers from 1-10
Square is invoked with the expression Square(i)
13Program Output
Number Square 1 1 2 4 3 9 4
16 5 25 6 36 7 49 8
64 9 81 10 100
146.4 Function Procedures
- Format of a Function procedure definition
- Function procedure-name(parameter-list) As
return-type - declarations and statements
- End Function
- Return-type Indicates the data type of the
result returned from the Function to its caller - Return expression
- Can occur anywhere in a Function
- It returns exactly one value
- Control returns immediately to the point at which
that procedure was invoked
15Common Errors
- If the expression in a Return statement cannot be
converted to the Function procedures
return-type, a runtime error is generated. - Failure to return a value from a Function
procedure (e.g., by forgetting to provide a
Return statement) causes the procedure to return
the default value for the return-type, often
producing incorrect output.
166.5 Methods
- Definition of method
- A method is any procedure that is contained
within a class - FCL methods
- Custom methods in programmer-defined classes
17- 1 ' Fig. 6.4 Maximum.vb
- 2 ' Program finds the maximum of three numbers
input. - 3
- 4 Public Class FrmMaximum
- 5
- 6 ' obtain values in each text box, call
procedure Maximum - 7 Private Sub btnMaximum_Click(ByVal sender
As System.Object, ByVal e As System.EventArgs)
Handles btnMaximum.Click - 8 Dim value1, value2, value3 As
Double - 9
- 10 value1 txtFirst.Text
- 11 value2 txtSecond.Text
- 12 value3 txtThird.Text
- 13
- 14 lblMaximum.Text Maximum(value1,
value2, value3) - 15 End Sub ' cmdMaximum_Click
- 16
- 17 ' find maximum of three parameter values
- 18 Function Maximum(ByVal valueOne As
Double, ByVal valueTwo As Double, ByVal
valueThree As Double) - 19
Event handler btnMaximum_Click Handles the event
in which Button btnMaximum is clicked
18(No Transcript)
196.5 Methods
It is not necessary to add an assembly reference
to use the Math class methods in a program,
because class Math is located in namespace
System, which is implicitly added to all console
applications.
Fig. 6.7 Math class methods.
206.6 Argument Promotion
- Coercion of arguments
- The forcing of arguments to be appropriate data
type so that they can be passed to a procedure.
Visual Basic supports both - Widening conversion
- Occurs when a type is converted to another type
without losing data - Narrowing conversion
- Occurs when there is potential for data loss
during the conversion
21Widening conversion
- Math class method Sqrt can be called with an
Integer argument, even though the method is
defined in the Math class to receive a Double
argument. - The statement
- Console.Write(Math.Sqrt(4))
- correctly evaluates Math.Sqrt(4) and prints
the value 2. - Visual Basic promotes (i.e., converts) the
Integer value 4 to the Double value 4.0 before
the value is passed to Math.Sqrt. - In this case, the argument value does not
correspond precisely to the parameter type in the
method definition, so an implicit widening
conversion changes the value to the proper type
before the method is called.
22Narrowing conversion
- Visual Basic also performs narrowing conversions
- on arguments passed to procedures.
- For example, if String variable number contains
- the value "4", the method call
Math.Sqrt(number) correctly evaluates to 2. - However, some implicit narrowing conversions can
fail, resulting in runtime errors and logic
errors. - For example, if number contains the value
"hello", passing it as an argument to method
Math.Sqrt causes a runtime error.
236.6 Argument Promotion
Fig. 6.8 Widening conversions.
246.6 Argument Promotion
- In mixed-type expressions, each value is promoted
to the highest data type in the expression
(i.e., widening conversions are made until the
values are of the same type). - For example, if singleNumber is of type Single
and integerNumber is of type Integer, when Visual
Basic evaluates the expression - singleNumber integerNumber
- the value of integerNumber is converted to
type Single, then added to single-Number,
producing a Single result. - Although the values original data types are
maintained, a temporary version of each value is
created for use in the expression, and the data
types of the temporary versions are modified
appropriately.
256.7 Option Strict and Data-Type Conversions
- Visual Basic provides several options for
controlling the way the compiler handles data
types. - These options can help programmers eliminate
such errors as those caused by narrowing
conversions, making code more reliable and secure.
266.7 Option Strict and Data-Type Conversions
- Option Explicit
- Set to On by default
- Forces the programmer to declare explicitly all
variables before they are used - Option strict
- Set to Off by default
- When set to On, it forces the programmer to
perform an explicit conversion for all narrowing
conversions
276.7 Option Strict and Data-Type Conversions
Option Strict can be activated through the IDE by
right-clicking the project name in the Solution
Explorer. From the resulting menu, select
Properties to open the Property Pages
dialog. From the directory tree on the left side
of the dialog, select Build from the Common
Properties list. In the middle of the dialog is a
drop-down box labeled Option Strict. By default,
the option is set to Off. Choose On from the
dropdown box and press Apply.
286.8 Value Types and Reference Types
All Visual Basic data types can be categorized as
either
- Variable of a value type
- Contains the actual data
- Used for a single piece of data
- Integer
- Double
- Variable of a reference type
- Contains a location in memory where data is
stored. - Known as objects
296.8 Value Types and Reference Types
- Both value types and reference types include
built-in types and types that the programmer can
create. - The built-in value types include
- the integral types (Byte, Short, Integer and
Long), - the floating-point types (Single and Double)
- and types Boolean, Date, Decimal and Char.
- The built-in reference types include
- Object
- and String.
- The value types that can be constructed by the
programmer include Structures and Enumerations. - The reference types that can be created by the
programmer - include classes, interfaces and delegates.
306.8 Value Types and Reference Types
- Literals
- Values typed directly in program code
- Each literal corresponds to one of the primitive
data types. - Some of Visual Basics data types use special
notations for - creating literals.
- For instance, to create a literal of type Char,
follow a single- - character String with the type character c.
- The statement Dim character As Char "Z"c
- declares Char variable character and
initializes it to the "Z" - character.
316.8 Value Types and Reference Types
Fig. 6.11 Literals with type characters.
326.9 Passing Arguments Pass-by-Value vs.
Pass-by-Reference
- Pass-by-value
- The program makes a copy of the arguments value
and passes that copy to the called procedure - changes to the called procedures copy do not
affect the original variables value. - Pass-by-reference
- The caller gives the called procedure the ability
to access and modify the callers original data
directly.
33- 1 ' Fig. 6.12 ByRefTest.vb
- 2 ' Demonstrates passing by reference.
- 3
- 4 Module modByRefTest
- 5
- 6 ' squares three values ByVal and ByRef,
displays results - 7 Sub Main()
- 8 Dim number1 As Integer 2
- 9
- 10 Console.WriteLine("Passing a
value-type argument by value") - 11 Console.WriteLine("Before calling
SquareByValue, " _ - 12 "number1 is 0", number1)
- 13 SquareByValue(number1) ' passes
number1 by value - 14 Console.WriteLine("After returning
from SquareByValue, " _ - 15 "number1 is 0" vbCrLf, number1)
- 16
- 17 Dim number2 As Integer 2
- 18
- 19 Console.WriteLine("Passing a
value-type argument" _
When number1 is passed, a copy of the value is
passed to the procedure
A reference to the value stored in number2 is
being passed
34- 29 Console.WriteLine("Passing a
value-type argument" _ - 30 " by reference, but in
parentheses") - 31 Console.WriteLine("Before calling
SquareByReference " _ - 32 "using parentheses, number3 is
0", number3) - 33 SquareByReference((number3)) ' passes
number3 by value - 34 Console.WriteLine("After returning
from " _ - 35 "SquareByReference, number3 is
0", number3) - 36
- 37 End Sub ' Main
- 38
- 39 ' squares number by value (note ByVal
keyword) - 40 Sub SquareByValue(ByVal number As
Integer) - 41 Console.WriteLine("After entering
SquareByValue, " _ - 42 "number is 0", number)
- 43 number number
- 44 Console.WriteLine("Before exiting
SquareByValue, " _ - 45 "number is 0", number)
- 46 End Sub ' SquareByValue
- 47
Enclosing arguments in parenthesis forces
pass-by-value even if using ByRef
ByVal indicates that value-type arguments should
be passed by value
ByRef gives direct access to the value stored in
the original variable
35Program Output
- Passing a value-type argument by value
- Before calling SquareByValue, number1 is 2
- After entering SquareByValue, number is 2
- Before exiting SquareByValue, number is 4
- After returning from SquareByValue, number1 is 2
-
- Passing a value-type argument by reference
- Before calling SquareByReference, number2 is 2
- After entering SquareByReference, number is 2
- Before exiting SquareByReference, number is 4
- After returning from SquareByReference, number2
is 4 -
- Passing a value-type argument by reference, but
in parentheses - Before calling SquareByReference using
parentheses, number3 is 2 - After entering SquareByReference, number is 2
- Before exiting SquareByReference, number is 4
- After returning from SquareByReference, number3
is 2
366.9 Passing Arguments Pass-by-Value vs.
Pass-by-Reference
- Passing value-type arguments with keyword ByRef
is useful when procedures need to alter argument
values directly. However, passing by reference
can weaken security, because the called procedure
can modify the callers data. - Reference-type variables passed with keyword
ByVal are effectively passed by reference, as the
value that is copied is the reference for the
object. - Although Visual Basic allows programmers to use
keyword ByRef with reference-type parameters, it
is usually not necessary to do so except with
type String.
376.10 Duration of Identifiers
- Identifiers duration Period during which the
identifier exists in memory - Automatic duration
- Identifiers that represent local variables in a
procedure have automatic duration - Instance variable
- A variable declared in a class
- They exist as long as their containing class is
loaded in memory - Identifiers scope Portion of a program in which
the variables identifier can be referenced
386.11 Scope Rules
- Possible scopes
- Class scope
- Begins at the class identifier after keyword
Class and terminates at the End Class statement - Module scope
- Variable declared in a module have module scope,
which is similar to class scope - Namespace scope
- Procedures defined in a module have namespace
scope, which generally means that they may be
accessed throughout a project - Block scope
- Identifiers declared inside a block, such as the
body of a procedure definition or the body of an
If/Then selection structure, have block scope
39- 1 ' Fig. 6.13 Scoping.vb
- 2 ' Demonstrates scope rules and instance
variables. - 3
- 4 Public Class FrmScoping
- 5 Inherits System.Windows.Forms.Form
- 6
- 7 Friend WithEvents lblOutput As
System.Windows.Forms.Label - 8
- 9 ' Windows Form Designer generated code
- 10
- 11 ' instance variable can be used anywhere
in class - 12 Dim value As Integer 1
- 13
- 14 ' demonstrates class scope and block
scope - 15 Private Sub FrmScoping_Load(ByVal sender
As System.Object, _ - 16 ByVal e As System.EventArgs) Handles
MyBase.Load - 17
- 18 ' variable local to FrmScoping_Load
hides instance variable - 19 Dim value As Integer 5
This variable is hidden in any procedure that
declares a variable named value
40- 32 ' automatic local variable value hides
instance variable - 34 Sub MethodA()
- 35 Dim value As Integer 25 '
initialized after each call - 36
- 37 lblOutput.Text vbCrLf vbCrLf
"local variable " _ - 38 "value in MethodA is " value "
after entering MethodA" - 39 value 1
- 40 lblOutput.Text vbCrLf "local
variable " _ - 41 "value in MethodA is " value "
before exiting MethodA" - 42 End Sub ' MethodA
- 43
- 44 ' uses instance variable value
- 45 Sub MethodB()
- 46 lblOutput.Text vbCrLf vbCrLf
"instance variable" _ - 47 " value is " value " after
entering MethodB" - 48 value 10
- 49 lblOutput.Text vbCrLf "instance
variable " _ - 50 "value is " value " before
exiting MethodB" - 51 End Sub ' MethodB
Automatic variable value is destroyed when
MethodA terminates
When MethodB procedure refers to variable value,
the instance variable value (line 12) is used.
41(No Transcript)
42Conclusion
- Experience has shown that the best way to develop
and maintain a large program is to construct it
from small, manageable pieces. This technique is
known as divide and conquer. - Visual Basic programs consist of many pieces,
including modules and classes. - Three types of procedures exist Sub procedures,
Function procedures and event procedures.
43Conclusion
- The characteristics of Function procedures are
similar to those of Sub procedures. However, - Function procedures return a value to the
caller. - If a Function procedure body does not specify a
Return statement, program control returns to the
point at which a procedure was invoked when the
End Function keywords are encountered.
44Conclusion
- An event represents a user action, such as the
clicking of a button. - Widening conversion occurs when a type is
converted to another type without losing data. - Narrowing conversion occurs when there is
potential for data loss during a conversion. - Some narrowing conversions can fail, resulting in
runtime errors and logic errors.
45Conclusion
- Option Explicit, which is set to On by default,
forces the programmer to declare all variables
explicitly before they are used in a program. - Forcing explicit declarations eliminates spelling
errors and other subtle errors that may occur if
Option Explicit is turned Off. - Option Strict, which is set to Off by default,
increases program clarity and reduces debugging
time. - When set to On, Option Strict requires the
programmer to perform all narrowing conversions
explicitly.
46Conclusion
- All data types can be categorized as either value
types or reference types. - A variable of a value type contains data of that
type. - A variable of a reference type contains the
location in memory where the data is stored. - Both value and reference types include built-in
types and types that programmers can create. - Values typed directly in program code are called
literals. - Each literal corresponds to one of the primitive
data types. Some of Visual Basics data types use
special notations, such as type characters, for
creating literals.
47Conclusion
- Arguments are passed in one of two ways
Pass-by-value and pass-by-reference. - When an argument is passed by value, the program
makes a copy of the arguments value and passes
that copy to the called procedure. Changes to the
called procedures copy do not affect the
original variables value. - When an argument is passed by reference, the
caller gives the procedure the ability to access
and modify the callers original data directly. - Pass-by-reference can improve performance,
because it eliminates the need to copy large data
items, such as large objects however,
pass-by-reference can weaken security, because
the called procedure can modify the callers
data.
48Conclusion
- Value-type arguments enclosed in parentheses, (),
are passed by value even if the procedure header
declares the parameter with keyword ByRef. - An identifiers duration (also called its
lifetime) is the period during which the
identifier exists in memory. - Identifiers that represent local variables in a
procedure (i.e., parameters and variables
declared in the procedure body) have automatic
duration. - Automatic-duration variables are created when
program - control enters the procedure in which they
are declared, exist while the procedure is active
and are destroyed when the procedure is exited.
49Conclusion
- The scope of a variable, reference or procedure
identifier is the portion of the program in which
the identifier can be accessed. - The possible scopes for an identifier are class
scope, module scope, namespace scope and block
scope.