230 likes | 338 Views
Sub Procedures and functions. Sub procedures. An event procedure is a sub procedure written for a specific object event ( ie . buttons, textboxes) Sub procedures can also perform tasks not related to a specific event
E N D
Sub procedures • An event procedure is a sub procedure written for a specific object event (ie. buttons, textboxes) • Sub procedures can also perform tasks not related to a specific event • Sub procedures provide a way to break up long coding segments, reduce repeated code and make programs more flexible • The breaking up of a program is called modularization
Sub procedures • Sub procedures use the following syntax: • Sub ProcedureName() • statements • End Sub • ProcedureName describes the task performed by the procedure • Statements is one or more statements that perform the task
Sub procedures • The code is more flexible because changes to the statements only need to be made in a single sub procedure, not every procedure that needs the code • Sub FormNotComplete() • Messagebox.show(“Please complete all textboxes”) • End Sub • A Sub procedure must be called from another procedure • Call FormNotComplete() - the word Call is optional, but • the parenthesis are required • When the sub is called, its code statements are executed
Value Parameters • Data is passed to a procedure by enclosing it in parentheses in the calling procedure • A value passed to a procedure is called an argument • Call GiveHint(intSecretNumber, intGuess) • The Sub procedure is declared with parameters that assume the values from the arguments that are passed • Sub GiveHint(ByValintFirstNum As Integer, By Val • intSecondNum As Integer) • IntFirstNum takes on the value of intSecretNumber • IntSecondNum takes on the value of intGuess
Value Parameters • The number of arguments in a procedure call MUST match the number of parameters in the procedure declaration • The order of the arguments passed corresponds to the order of the parameters • IMPORTANT: the number, data type and order of the arguments MUST match the number, data type and order of the parameters
Private Sub btnGuess(…..) • Dim gen as new random • Static intSecretNum As Integer = gen.next(1, 101) • Dim intGuess as Integer = Val(txtGuess.text) • Call GiveHint(intSecretNum, intGuess) • If intGuess = intSecretNum then • lblAnswer.text = “You guessed it!” • End If • End Sub • Sub GiveHint(ByValintFirstNum As Integer, ByValintSecondNum As Integer) • If intFirstNum > intSecondNum Then • MessageBox.Show (“Too low”) • Else • MessageBox.Show(“Too high”) • End Sub • In this example, intFirstNum takes on the value of intSecretNum and intSecondNum takes on the value of intGuess
Different arguments can be passed: variables, formulas • and constants • Call GiveHint(intSecretNumber, intGuess) • Call GiveHint(2*5, 10*2) • Call GiveHint(10, intGuess) • Call GiveHint(10,20)
Value Parameters • Passes the value of the variable to the sub procedure – does NOT pass the variable itself – creates a new place in memory for the parameter variable • The value of the original variable is not changed – it remains separate with its own value (think of it as a local variable) • Use ByVal when no return value is needed • Think of ByVal as a “one way street”
Sub Demo() • Dim intCounter As Integer = 1 • Call ShowCount(intCounter) • Me.lblNumber.Text = intCounter ‘ displays 1 • End Sub • Sub ShowCount(ByValintCounter As Integer) • intCounter = intCounter + 1 • MessageBox.Show(intCounter) ‘displays 2 • End Sub
Reference Parameters • Represents the same storage location as the variable give in the procedure call – CHANGES the value of the variable • Passing ByRef passes a reference to the variable itself • ByRef parameters only accept variable arguments • Think of ByRef as a “Two Way Street” because the value comes back to the original variable • Example of when to use ByRef: when calculating interest on a debt, the interest amount is returned to the main calling procedure where it is then added to the debt to calculate a payment. • A procedure can have both ByVal and ByRef parameters
A procedure that send values back to the calling procedure uses reference parameters • Reference parameters can alter the value of the actual variables used in the procedure call. • Private Sub btnAdd • Dim intFirstNumas Integer = Val(txtFirst.text) • Dim intSecondNum as integer = val(txtSecond.text) • Dim intResult as integer • Call Add(intFirstNum, intSecondNum, intResult) • lblAnswer.text = intResult • End Sub • Sub Add (ByValintone As Integer, ByValintTwo as integer, ByRefintSum as Integer) • intSum= intOne + intTwo • End Sub
Procedure Documentation • Precondition • Assumptions or initial requirements of a procedure. • You should include preconditions above your procedure. • Example:PRE: x is an Integer and x > 0 • Postcondition • A statement of what must be true at the end of the execution of a procedure if the procedure has worked properly. • You should include preconditions above your procedure. • Example:POST: Result is calculated
Strong Typing In the previous examples, strong typing was used. This is assigning a data type to ALL variables including those in procedure calls. This is strongly recommended.
Strong Typing According to Microsoft . . . • It enables IntelliSense support for your variables and parameters. • This allows you to see their properties and other members as you type in your code. • It allows the compiler to perform type checking. • This helps catch statements that can fail at run time due to errors such as overflow. • It also catches calls to methods on objects that do not support them. • It results in faster execution of your code. • One reason for this is that if you do not specify a data type for a programming element, the Visual Basic compiler assigns it the Object type. • Your compiled code might have to convert back and forth between Object and other data types, which reduces performance.
Option Strict • To enforce strong typing by default (the IDE will require all variables to have data types declared) turn on Option Strict. • Type Option Strict On before all other code. • In ToolsOptionsProjects and SolutionsVB Defaults Option Strict can be turned on by default for all programs. • This also requires all conversions between data types be stated- not inferred. Examples given in these PowerPoint follow this rule using the Convert keyword or the ToString() method.
Functions Computer Programming 1
Functions • Functions are a special type of procedure that return a value to the main program using a return statement. • Functions must be given a data type when declared. The function ends with an “End Function” statement. FunctionProcedureName(ByValparam1As type,…) As ReturnType Statements Returnvalue End Function
Functions • Functions are called from within a statement that will make use of the return value. • The order of the arguments corresponds to the order of the parameters. • Only ByVal parameters should be declared in a function because a function should not alter the arguments it has been passed. • A function returns a single value and therefore must be used in a statement such as an assignment statement that makes use of the returned value.
dblResult= Calculate(dblNum1, dblNum2) Calls a Function – returns a value • Calculate(dblNum1, dblNum2)Calls a sub procedure & does not return anything • An assignment statement is used to assign the function (which returns a value) to a variable. • A sub procedure does not return a value.
Function Calculate(ByVal dblNum1 As Double, ByVal dblNum2 As Double) As Double • The function call itself is given above. Remember all functions must be given a data type after the parameters. • Formal arguments/parameters are always ByVal. • Last line of a function is always a statement with the Return keyword: Return dblResult
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim sngNum1, sngNum2, sngResult As Single 'Validates input from the text boxes Try sngNum1 = (txt1.Text) sngNum2 = (txt2.Text) sngResult = Calculate(sngNum1, sngNum2) 'Calls the Function lblResult.Text = sngResult Catch ex As Exception MessageBox.Show("Enter numeric values in both textboxes") End Try End Sub Continued….
Sample Code Function Calculate(ByVal sngNum1 As Single, ByVal sngNum2 As Single) As Single Dim sngResult as SinglesngResult = sngNum1 + sngNum2 'Return sngResultto the main program Return sngResult End Function