9
Procedures and Scope Reading Terms you should know: Procedure, Method, Function, Sub Procedure, Procedure Header, Procedure Name, Procedure Call, ByVal, ByRef, Parameter, Parameter List, Argument, Procedure Body, Step Into, Step Out, Step Over, Break Points. Procedures (i.e. methods) In VB procedures are of two types, 1) Functions – which return a value to the calling code and 2) Sub procedures which don’t return a value to the calling program. Now this doesn’t mean a sub procedure can’t be used to create an output for the application’s user but the sub procedures don’t return values to the code itself. Procedures are also called “methods” in OO speak and I’ll be using these terms interchangeably. Procedures/methods do something specific for you, they are actions, so it is customary to give them verb names. For example, SquareRoot or CalculateValue or FillByEmail. As you may suspect you have already used many pre-defined sub procedures, like button click events. You’ve used many functions too, like the Val function, and the Fillby and GetDataBy of your select queries. In this reading I’ll explain all the pieces of a procedure call and header so that you can comfortably create and use your own procedures be they functions or sub procedures. We’ll begin with some examples. Function Example Function Square (ByVal input as Double) As Double Return input^2 End Function What does this procedure do? It returns the square of a provided value. Here are the different parts: 1. The Procedure Header: Function Square(ByVal input as Double) As Double a. “Function” is a Keyword that you aren’t allowed to use in any other way b. The Procedure name is “Square” c. “(ByVal input as Double)” i. ByVal”– says that a copy of the inputted value should be passed to Square rather than using, and perhaps altering, the original value ii. “Input as Double” - here a new variable, named input, with procedure scope is being created and declared as type double. The value being passed to the procedure is called a parameter. Were there more than one input needed these variables declarations would be separated by commas to create a parameter list. d. The second “As Double” specifies the return type, (i.e. the result returned to the calling code will be of type double) 2. The Procedure Body “Return input ^ 2” - actually performs the calculation. a. “Return” is a keyword that returns the result of the following expression. This is required in a function but isn’t used at all in a sub procedure. As soon as you see the “return” keyword you know you’re working with a function 3. The function ends with Keyword “End Function”

Procedures and Scope Reading

Embed Size (px)

DESCRIPTION

it

Citation preview

  • Procedures and Scope Reading

    Terms you should know: Procedure, Method, Function, Sub Procedure, Procedure Header, Procedure Name,

    Procedure Call, ByVal, ByRef, Parameter, Parameter List, Argument, Procedure Body, Step Into, Step Out, Step

    Over, Break Points.

    Procedures (i.e. methods)

    In VB procedures are of two types, 1) Functions which return a value to the calling code and 2) Sub procedures which dont return a value to the calling program. Now this doesnt mean a sub procedure cant be used to create an output for the applications user but the sub procedures dont return values to the code itself. Procedures are also called methods in OO speak and Ill be using these terms interchangeably. Procedures/methods do something specific for you, they are actions, so it is customary to give them verb names. For example, SquareRoot or CalculateValue or FillByEmail. As you may suspect you have already used many pre-defined sub procedures, like button click events. Youve used many functions too, like the Val function, and the Fillby and GetDataBy of your select queries. In this reading Ill explain all the pieces of a procedure call and header so that you can comfortably create and use your own procedures be they functions or sub procedures. Well begin with some examples.

    Function Example

    Function Square (ByVal input as Double) As Double Return input^2 End Function What does this procedure do? It returns the square of a provided value. Here are the different parts:

    1. The Procedure Header: Function Square(ByVal input as Double) As Double

    a. Function is a Keyword that you arent allowed to use in any other way b. The Procedure name is Square c. (ByVal input as Double)

    i. ByVal says that a copy of the inputted value should be passed to Square rather than using, and perhaps altering, the original value

    ii. Input as Double - here a new variable, named input, with procedure scope is being created and declared as type double. The value being passed to the procedure is called a parameter. Were there more than one input needed these variables declarations would be separated by commas to create a parameter list.

    d. The second As Double specifies the return type, (i.e. the result returned to the calling code will be of type double)

    2. The Procedure Body Return input ^ 2 - actually performs the calculation. a. Return is a keyword that returns the result of the following expression. This is required in a

    function but isnt used at all in a sub procedure. As soon as you see the return keyword you know youre working with a function

    3. The function ends with Keyword End Function

  • Sub procedure example

    Sub CalculateWage (ByVal HoursWorked as decimal, ByVal HourlyWage as decimal)

    Wage = HoursWorked * HourlyWage Wagetextbox.text = Wage

    End Sub

    1. The Procedure Header is: Sub CalculateWage (ByVal HoursWorked as decimal, ByVal HourlyWage as decimal)

    a. Sub is a Keyword that you arent allowed to use in any other way b. The Procedure name: CalculateWage c. Parameter List: (ByVal HoursWorked as decimal, ByVal HourlyWage as decimal)

    i. ByVal says copy of the inputted value should be passed to CalculateWage rather than using, and perhaps altering, the original value

    ii. HoursWorked as decimal, ByVal HourlyWage as decimal - here two new variables, named HoursWorked and HourlyWage, with procedure scope are created and declared as type double. This is the parameter list of inputs used by the method. You can thinking of these variables as catchers mitts waiting to catch the values you send to your method.

    iii. Note that the sub procedure header ends after the closed parentheses around the parameter listsub procedures dont return values to the code so we dont need to delare the data type of a return value.

    2. The Procedure Body the actions to be done: Wage = HoursWorked * HourlyWage Wagetextbox.text = Wage

    3. End Sub Reserved words that close off the sub procedure.

    Calling / Invoking a Procedure

    In order to use your procedures you need to call them in your code. A call specifies the procedure name and provides information (arguments) that the procedure needs to complete its job. Functions and sub procedures need slightly different calls. Below are two function call examples. We know they are function calls because they are each part of an assignment statement. Why is this? Because functions return a value to the calling code, we need a place-holding variable (Result and Wages in the examples below) to catch the value the function returns. Sub procedures dont have assignment statements in their calls because they dont return anything to the calling code. Function Call Examples: Result = val(inputTextBox.Text) SquaredNumber = Calculate_Square(User_Given_Number) A procedure call also includes the arguments the procedure needsthese are inputtextbox.textand User_Given_Number in the examples above. Youve called at least one of these functions before, the Val function. But what would a sub procedure call look like? Its very similar to the function calls above but no assignment statement or output receiving variable is needed. Sub Procedure Call examples: CalculateWage(Hours, RatePerHour)

  • PrintGrade(StudentPercentage) In the above calls, Hours, RatePerHour, and StudentPercentage are all arguments that are being passed to their respective procedures. Now you may be wondering about the difference between a parameter and an argument. Heres an explanation from Microsofts Visual Studio help page (http://msdn.microsoft.com/en-us/library/9kewt1b3.aspx)

    In most cases, a procedure must have some information about the circumstances in which it has been

    called. A procedure that performs repeated or shared tasks uses different information for each call. This

    information consists of variables, constants, and expressions that you pass to the procedure when you call

    it.

    To communicate this information to the procedure, the procedure defines a parameter, and the calling

    code passes an argument to that parameter. You can think of the parameter as a parking space and the

    argument as an automobile. Just as different automobiles can park in a parking space at different times,

    the calling code can pass a different argument to the same parameter every time that it calls the

    procedure.

    The number of arguments in the procedure call must match the parameters in the procedure header and must be of compatible type. Not the exact same type but a compatible type. For example, The sub procedure call: CalculateWage(Hours, RatePerHour) The matching header: Sub CalculateWage (ByVal HoursWorked as decimal, ByVal HourlyWage _ as decimal) Given the above call and header, a copy of the value stored in Hours will be placed in the variable

    HoursWorked. Similarly, a copy of the value in RatePerHour will be placed into HourlyWage. For this to work,

    both Hours and RatePerHour will need to have been declared as a data type such as decimal or some other

    data type compatible with decimal. Also, notice that the argument names in the call dont match the

    parameter names in the header. They dont have tosince the ByVal ensures we are only making a copy of

    the values stored in the call variables (arguments) for use in our sub procedure theres no implication to

    matching the variable names in the call and header. You can match them if you want to but its just not

    necessary. Further, if you do name them the same as shown below, it doesnt matter because the variables

    declared in the procedure header really only exist in this procedure and not outside it so even if they share the

    same name theres no risk of over-writing or modifying the variables in the calling code. So match the variable

    names (like below) or dont match them (like above) it really doesnt matter.

    The call: CalculateWage(Hours, RatePerHour) The matching header: Sub CalculateWage (ByVal Hours as decimal, ByVal RatePerHour _ as decimal)

    So what happens when a procedure is called? Control is passed to the called procedurethis overrides the sequence control structure in the execution of the code. Then the procedure runs. Once the procedure is finished, the application continues execution at the point where the procedure call was made. This is importantThe procedure call is just another line of code to the compilerthis is why we have the assignment

  • statement written the way it is for functionsbecause after the function executes well pop out of it right at the call and then execute the assignment statement that assigns the returned value to our waiting variable.

    Debugging Procedures

    Stepping Through Code there are several options for testing and debugging code. They are Step Into, Step Over, and Step Out and are used in conjunction with breakpoints. These are particularly helpful in testing code that includes procedures. By stepping through code the debugger will execute each line of code following a breakpoint. Step Into lets you enter a procedure and execute each statement in the procedure one by one. If theres a problem with your procedure, Step Into is a good way to figure out why your procedure isnt giving you what you want. Step Over executes code line by line as long as there isnt a procedure call. If a procedure call is encountered, the procedure is executed all at once, not line by line. This is a time saver if you are using previously tested procedures that you know are fine. In OO programming we are often using lots of predefined procedures we know work so why test them again and again? Step Over lets you test the code around it and assume the procedure is doing its job well. Step Out if you have used Step In, Step Out lets you jump out of a procedure after youve checked a few lines of code. It will complete remaining lines of code in your procedure all at once and return to you to the calling code.

    Passing Arguments to Procedures

    I have mentioned this already but many students find Pass by Value vs. Pass by Reference (ByVal vs. ByRef) confusing so here is more detail. There are two ways to pass arguments to procedures. ByVal which means the argument is passed by value. A copy of the value is made for use in the procedure and the value of the original argument is left changed. This is the most commonly used option. With ByRef no copy of the argument is made, rather the original data can be accessed and modified directly by the called procedure. Use ByRef with caution. Another interesting use of ByRef is that it can be used in conjunction with sub procedures that will allow your sub procedure to influence your calling code. Remember, sub procedures dont return a value to the calling code, only functions do, but with ByRef we are overwriting the value stored in the original variable with a value created by the procedure. So if we use ByRef we can simulate, in a manner of speaking, a functions ability to return a value to the calling code with a sub procedure but we are doing so by overwriting a variable value in the calling code rather than actually sending a value to it as we would in a function.

    Variable scope Important terms: scope, public variables, module scope, instance variables, procedure scope, local variables,

    block scope.

    Ahvariable scopeone of the most challenging concepts well cover in this class. So what is scope in this context anyway? Scope here is different than the project scope we discussed earlier in the semester. Here it is the portion of an application in which a variables identifier can be referenced. In VB, the different types of scope a variable may have are: 1. Throughout an entire application, like your course projectthese are public variables 2. Anywhere in a single form, these have module scope and are called instance variables. 3. Only in a single sub procedure or function these have procedure scope and are local variables 4. Only with a single block (like an if-then or loop)these have block scope and are also local variables

  • Scope Overview: 2 Main Types of Variables

    Are declared outside

    any procedure and have

    module scope

    If local and instance variables share the same

    name what happens while the block or procedure is

    executing?

    Have procedure scope, if

    declared within a procedure,

    or block scope, if declared

    within a repetition or selection

    structure

    Local VariablesInstance Variables

    So why does the distinction between local and instance variables matter? Because of how they interact with each other. Local variables only exist within procedures or blocks so code outside the procedure or block those cant alter them or even reference them. Similarly, in the main form code, the instance variables reign supreme and whatever you do to the local variables doesnt impact the instance variable values. This is why, as mentioned earlier, it doesnt matter if you name variables in procedure headers and procedure calls the same thingthey cant truly interact anyway. Once inside the procedure instance variables (those declared outside the procedure) that share names with local variables (those declared inside the procedure) are ignored until the procedure has finished executing. During the procedures execution only the local variables are available for use. Instance variables (these have module scope) are declared within a class (your form) but outside any procedure. This allows all procedures in that class to access that variable. Variables with module scope maintain their values between procedures. Local variables cant be accessed outside the procedure or block in which they are declared. So if you declare a variable within a button click sub procedure, that variable will not be available in other sub procedures. Such a variable has procedure scope. Procedure scope variables, are local variables declared inside a procedure but outside a control statement (like an if-then) and cannot be referenced outside the procedure in which they are declared. Parameters declared in a procedure header have procedure scope. Variables with block scope are declared inside a control statement (like an if then or a do while). Block scope begins at the variable declaration and ends at last line of the control.

    Controlling Access to Class Members

    Keywords Public and Private are called member-access modifiers. If youll recall, in VB we often use the reserved word Dim to declare variables. For example: Dim NumberOfCartons as Integer

  • However, such variables are Private and are not available to other classes such as other forms. The reserved word Public makes instance variables (or methods) accessible wherever the application has a reference to that object. Lets look at an example to clarify. Say you are on your Course project LoginForm. You declare a variable to hold the users email because youll need that not only to help them log in but also to retrieve other information from their record for the MemberAccount page. If you declare that variable as: Dim UserEmail as String then UserEmail is only available to your LoginForm. However, if we declare the like this: Public UserEmail as String then the variable can be referenced in other forms such as your MemberAccount form by referencing its full name: LoginForm.UserEmail. Remember, because UserEmail is declared on our LoginForm it belongs to class LoginForm. Thus its full name is its class, then the dot operator, then its variable name: LoginForm.UserEmail This is helpful but you need to be thoughtful in where you declare your public variables because code that cannot access any variable, even those declared as Public, if they are declared in a Private structure. For example, a Public variable in a Private structure is accessible from inside the class containing the structure, but not from outside that class. Luckily most of the classes you use are created as publicyour LoginForm is a public class so variables you declare as Public will be available to other forms. Methods (sub procedures and functions) can also be Private or Public. Most of the sub procedures you create, such as button click or text change events, will be Private. As with variables, methods declared Private are only accessible to other members of the current class. Most of the event handlers we have created have been Private as well since they are specific to the Forms class and not to the entire application.

    Data conversions

    A quick note about data conversions. There are three types: implicit conversion, widening conversions and narrowing conversions. Sometimes we can change data types without code (i.e. assign an Integer value to a decimal variable). This is called implicit conversion, but we can only do this when it makes sense such as assigning an integer to a text variable. Assigning a text variable to an integer variable however, causes an error. Widening Conversions occur when the value stored in a smaller variable type is assigned to a larger variable type (i.e. integer ->double, or integer to decimal). This is usually fine. Narrowing conversions occur when we assign a larger variable type value to a smaller variable type. This can cause a run time error or a logical error. For example, when converting a decimal to an integer via explicit narrowing conversion in VB, values are rounded (i.e. 5.7 becomes 6). In other languages such narrowing conversions are handled differently. In C# the same narrowing conversion of 5.7 to an integer and the .7 is truncated and thus the value becomes 5. This can obviously cause problems because information is lost and the values are inaccurate. You can prevent this from happening by turning on Option Strict. Option Strict disables narrowing conversions so youll get a syntax error (see, sometimes errors are actually good) rather than a logical error. To set Option Strict to on->Right Click project name->properties->compile option->option strict to on-> save all. The errors youll get with Option Strict and narrowing conversions will be either InvalidCastException or OverflowException.

  • Procedure Call Practice

    Your final exam in 110A is a multiple choice exam so while I cannot require you to be able to write your own

    procedure calls and headers in this format , you will be asked to examine a given procedure header (or call)

    and find its correct matching call (or header). I may also ask you to find error in either procedure headers or

    calls. Below are some exercises you can try to build your understanding of procedure calls and headers. I will

    include answers to these exercises at the end of this document. In the practice dont worry if your variable

    names are different than mine.

    1. What should the procedure call look like given the following procedure header?

    Total = AddNumbers(x,y,z)

    2. What should the procedure header look like given the following procedure call?

    Sub PrintSum(ByVal Total as Decimal)

    3. What should the procedure call look like given the following procedure header?

    Sub CalcSalary (ByVal BasePay as Decimal, ByVal Overtime as Decimal) 4. Assume the following procedure calculates and returns the overtime amount. What would the procedure header look like given the following call? TotalOT = CalcOT (Hours, OvertimePayRate) 5. Write a full procedure that multiplies a given number by two and returns the product to the calling code

    then write the call.

    Scope Practice

    On the exam you will be asked to identify the type of scope different variables have. Here are some practice

    questions to help you.

    1. What type of scope does a variable declared within an If-then statement have?

    2. What type of scope does a variable declared within a procedure have?

    3. What happens if an application tries to use a local variable outside its defining procedure or control

    statement?

    4. What kind or kinds of scope may local variables have?

    5. What type of scope does an instance variable have?

  • Procedure Call Practice Answers

    1. What should the procedure call look like given the following procedure header?

    Total = AddNumbers(x,y,z)

    Answer: Function AddNumbers (Byval Num1 As Decimal, ByVal Num2 As Decimal, ByVal Num3 As Decimal) As Decimal

    2. What should the procedure header look like given the following procedure call?

    Sub PrintSum(ByVal Total as Decimal)

    Answer: PrintSum(Sum)

    3. What should the procedure call look like given the following procedure header?

    Sub CalcSalary (ByVal BasePay as Decimal, ByVal Overtime as Decimal) Answer: CalcSalary(BaseSalary, OT) 4. Assume the following procedure calculates and returns the overtime amount. What would the procedure header look like given the following call? TotalOT = CalcOT (Hours, OvertimePayRate) Answer: Function CalcOT(ByVal Hours_Worked as decimal, ByVal OTPayRate as decimal) as Decimal 5. Write a full procedure that multiplies a given number by two and returns the product to the calling code then write the call. Answer: Function CalcProduct (ByVal Given as Decimal) as Decimal Return Given *2 End Function MultipliedValue = CalcProduct (Num1)

  • Scope Practice Answers

    1. What type of scope does a variable declared within an If-then statement have? Answer: Block scope

    2. What type of scope does a variable declared within a procedure have? Answer: Procedure scope

    3. What happens if an application tries to use a local variable outside its defining procedure or control

    statement? Answer: Variables declared inside Private procedures will not be available for use by the

    outside code. Variables with block scope will not be available to code outside the control statement.

    4. What kind or kinds of scope may local variables have? Answer: Procedure or Block Scope

    5. What type of scope does an instance variable have? Answer: Module Scope

    6. A variable declared inside a class but outside any procedure is called a(n) ____________ and has

    ___________ scope. Answer: Instance Variable, Module Scope