Download presentation
Presentation is loading. Please wait.
Published byGiles Gordon Modified over 8 years ago
1
IMS 3253: Subroutines 1 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Topics Procedures Subroutines Parameters –By Value and By Reference –Objects as Parameters Functions “Unix was not designed to stop you from doing stupid things, because that would also stop you from doing clever things.” Doug Gwyn
2
IMS 3253: Subroutines 2 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Procedures Functions and Subroutines are generically referred to as procedures –Includes the Event Procedures that we have been working with Writing procedures is one of the most fundamentally important skills we need in application development –Reuse code –Move code that isn’t important to the application logic into a separate location –Critical to understanding object oriented coding
3
IMS 3253: Subroutines 3 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Procedures (cont.) A procedure lets us package code into its own named location –The code in the named location can be “invoked” (run) on command –This is what happens in event procedures such as button click events Private Sub MyProcedure() End Sub
4
IMS 3253: Subroutines 4 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Procedures—What You Need to Know How to write subroutines and functions How to cause a subroutine to run How to cause a function to run Passing parameters to procedures and how they are used –By Reference –By Value Return values of functions Scoping procedures Remember, “procedures” includes subroutines, functions, and class properties
5
IMS 3253: Subroutines 5 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Subroutines Subroutines are packages of code that do not return a value back to the code that calls them They execute the code they contain Subroutines may affect values in the calling code through appropriate use of parameters (later)
6
IMS 3253: Subroutines 6 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Creating a Subroutine Subroutines consist of three parts –Subroutine declaration –Body of the subroutine –End Sub statement Private Sub SubName (argument list) ‘************************** ‘* Comment for sub ‘************************** End Sub
7
IMS 3253: Subroutines 7 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Creating a Subroutine (cont.) The Subroutine Declaration –“Private” means the subroutine can only be called by code within the current form (or class—later) –“Public” means the subroutine can be invoked by external code Important in multi-form applications And classes (object oriented programming) A public subroutine becomes a “method” Private Sub SubName (argument list)
8
IMS 3253: Subroutines 8 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Creating Subroutines (cont.) The Subroutine Declaration (cont.) –“Sub” is always required –“SubName” should describe the subroutine’s purpose –The argument list Contains the parameters for the subroutine (we will cover shortly) If there are no parameters the parentheses will be empty Private Sub SubName (argument list) Private Sub SubName ( )
9
IMS 3253: Subroutines 9 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Creating Subroutines (cont.) The subroutine body contains all of the code the subroutine will execute Any code you can write in an event procedure can be included in the subroutine The subroutine is aware of all controls on the form and can address them Variable scoping rules apply –The subroutine can address any module-level variables –The subroutine can have locally scoped variables –It cannot read local variables in other procedures
10
IMS 3253: Subroutines 10 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Running a Subroutine Two ways to cause a subroutine to run –Just state the subroutine name as the only statement on a line –Use the “Call” keyword –VB will add empty parentheses if you do not I insist that you use the “Call” keyword version –Increases readability –Distinguishes subroutine calls from other statements SubName (argument list) or SubName ( ) Call SubName (argument list) or Call SubName( )
11
IMS 3253: Subroutines 11 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu How Subroutines Work When a subroutine is called execution of the current sub is paused and execution branches to the first line of the subroutine The subroutine executes until either End Sub or Exit Sub is encountered Control then branches back to the line in the original (calling) code following the subroutine call Subroutines may call other subroutines up to several levels
12
IMS 3253: Subroutines 12 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu How Subroutines Work (cont.) Private Sub btnTest_Click (ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnTest.Click Call TestSubroutine() End Sub Private Sub TestSubroutine( ) <more code in the subroutine> End Sub 1 2 3 4
13
IMS 3253: Subroutines 13 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Subroutines and Error Handlers Try…Catch blocks have scope that pertains to subroutines –If the subroutine has a Try…Catch block it will try to handle any error –If the subroutine call is included in a Try…Catch block And the subroutine has no Try…Catch block –Or the subroutine doesn’t handle the error Then the calling code’s Try…Catch block will handle an error in the subroutine
14
IMS 3253: Subroutines 14 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Parameters One of the most powerful features of a procedure is the ability to accept parameters or arguments –Values passed from the calling code to the procedure –These values are available in the subroutine in locally scoped variables Call SubName(value) Private Sub SubName (ByVal ParamName As Datatype)
15
IMS 3253: Subroutines 15 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Parameters (cont.) Whatever is in value when the subroutine is called… …is passed to ParamName in the subroutine The subroutine can do anything with ParamName it could with any other locally scoped variable The value datatype must be compatible with the datatype specified for the parameter name (should be the same) Call SubName(value) Private Sub SubName (ByVal ParamName As Datatype)
16
IMS 3253: Subroutines 16 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Parameters (cont.) A subroutine may have a large number of parameters Almost any kind of value can be passed as a parameter –Including complex objects Controls Datasets (ISM 4212) Classes Arrays Forms Collections There is no requirement at all that the value have the same name in the calling code and subroutine
17
IMS 3253: Subroutines 17 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Parameters (cont.) Private Sub AddEmUpParams(ByVal FirstNum As Integer, _ ByVal SecondNum As Integer) Dim intResult As Integer '* Perform the calculation and display the result intResult = FirstNum + SecondNum lblResult.Text = intResult.ToString lblResult.BackColor = Color.LightGreen End Sub Private Sub btnParameter_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnParameter.Click Dim intFirstValue As Integer Dim intSecondValue As Integer '* Convert text values to integers intFirstValue = Convert.ToInt32(txtValueOne.Text) intSecondValue = Convert.ToInt32(txtValueTwo.Text) '* Call the subroutine to add the two numbers together Call AddEmUpParams(intFirstValue, intSecondValue) End Sub
18
IMS 3253: Subroutines 18 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Parameters—ByVal vs. ByRef By default, values are passed to subroutines by value (ByVal) A copy of the value is passed to the subroutine Any changes made to the local copy do not affect the value in the originating code Call SubName(strLastName) Private Sub SubName (ByVal LName As String)
19
IMS 3253: Subroutines 19 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Parameters—ByVal vs. ByRef (cont.) Values may be passed to subroutines by reference (ByRef) A reference to the memory location of the calling code’s value is passed Any changes made to the subroutine copy also change the value in the originating code –Both names (calling and subroutine) point to the same location in memory See sample project Call SubName(strLastName) Private Sub SubName (ByRef LName As String)
20
IMS 3253: Subroutines 20 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Passing Arrays as Parameters Arrays can be easily passed as parameters In the subroutine argument list indicate that the parameter is an array by following the name with empty parentheses –Do not indicate a size Omit the parentheses (just pass the array name) when the subroutine is called You usually must determine the array size in the subroutine Call SubName(sglDailySales) Private Sub SubName (ByRef Sales() as Single)
21
IMS 3253: Subroutines 21 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Passing Arrays as Parameters (cont.) Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim intTest(5) As Integer Dim x As Integer For x = 0 To 5 intTest(x) = x Next Me.TextBox1.Text = AddArray(intTest).ToString End Sub Private Function AddArray(ByVal thearray() As Integer) As Integer Dim intTotal As Integer Dim x As Integer For x = 0 To UBound(thearray) intTotal += thearray(x) Next Return intTotal End Function Just the array name (no parentheses) Array parameter name with empty parentheses
22
IMS 3253: Subroutines 22 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Optional Parameters Procedures may have optional parameters –No value is required when the procedure is called –A default value must be provided for the parameter in the procedure definition The default value must be a constant (literal) But the default value need not ever be used –If there is an optional parameter in the parameter list all subsequent parameters must also be optional Private Sub GradePoints(ByVal CrHr As Integer, _ ByVal LetterGrade As String, _ ByRef TotalGradePoints As Single, _ Optional ByVal ReplacedGrade As String = "")
23
IMS 3253: Subroutines 23 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Optional Parameters (cont.) When calling a procedure with optional parameters the last optional parameters can be completely omitted Intermediate parameters can be omitted with comma delimited arguments Private Sub TestSub(ByVal First As Integer, _ Optional ByVal Second As Integer = 0, _ Optional ByVal Third as Integer = 0) Call TestSub(1, 2, 3) Call TestSub(1, 2) Call TestSub(1,, 3) Call TestSub( ) All legal statements Illegal statement
24
IMS 3253: Subroutines 24 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Passing Objects as Parameters Objects can easily be passed as parameters by just specifying the correct object type as the datatype of the parameter When the subroutine is called pass the name of a specific object of the correct type Pass ByRef if the subroutine needs to change the object See sample project Private Sub ValidateInput(ByRef theTextBox As TextBox, _ ByVal ValidationString As String) Call ValidateInput(txtPrice, "0123456789.")
25
IMS 3253: Subroutines 25 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Functions Functions are just like subroutines except they can return a value The function’s results are inserted into the code where the function was called Private Function FunctionName ( ) As DataType Return End Function ‘* Call the function intResult = FunctionName( )
26
IMS 3253: Subroutines 26 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Functions (cont.) All rules for subroutine declarations apply to functions –Private or Public –Function instead of Sub –Name must be descriptive –All parameter rules apply No parameters, ByVal, ByRef, Optional The As DataType is new and required (by me) –As Boolean– As Integer –As String – etc. Private Function FunctionName ( ) As DataType
27
IMS 3253: Subroutines 27 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Functions (cont.) Functions will perform whatever processing is needed Will generate a value of the function’s datatype “Return value” will return the value as the function’s return value (result) Alternatively, Assigning a value to the function’s name within the body of the function also makes the value the function’s return value Private Function FunctionName ( ) As DataType
28
IMS 3253: Subroutines 28 Dr. Lawrence West, MIS Dept., University of Central Florida lwest@bus.ucf.edu Returning Multiple Values from a Function Functions will only return one object You can get around the limitation of returning just one value by being creative with coding constructs: –Return an array or collection –Return a complex object such as a class (later) Especially useful when dissimilar data types need to be returned –Return a single return value but use ByRef parameters to let the function actually affect more than one value that the calling code can see
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.