1 / 28

Topics

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. Procedures.

maxime
Télécharger la présentation

Topics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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. 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. 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() <code to execute> End Sub

  4. 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. 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. Creating a Subroutine • Subroutines consist of three parts • Subroutinedeclaration • Body of the subroutine • End Substatement Private Sub SubName (argument list) ‘************************** ‘* Comment for sub ‘************************** <code to run> End Sub

  7. Creating a Subroutine (cont.) Private Sub SubName (argument list) • 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”

  8. Creating Subroutines (cont.) Private Sub SubName (argument list) • 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 ( )

  9. 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. 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) orSubName ( ) Call SubName (argument list) or Call SubName( )

  11. 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. How Subroutines Work (cont.) Private Sub btnTest_Click (ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnTest.Click <code in the event procedure> Call TestSubroutine() <more code in the procedure> End Sub 1 Private Sub TestSubroutine( ) <code in the subroutine> <more code in the subroutine> <more code in the subroutine> <more code in the subroutine> End Sub 2 3 4

  13. 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. 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) <code that uses ParamName>

  15. Parameters (cont.) Call SubName(value) Private Sub SubName (ByVal ParamName As Datatype) <code that uses ParamName> • 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)

  16. 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. 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. 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. 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. 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. 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 emptyparentheses

  22. 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. 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. 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. 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 (<parameter list>) As DataType <processing code in the function> Return <value or object of same data type as function> End Function ‘* Call the function intResult = FunctionName(<parameters>)

  26. Functions (cont.) Private Function FunctionName (<parameter list>) As DataType • 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.

  27. Functions (cont.) Private Function FunctionName (<parameter list>) As DataType • 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

  28. 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

More Related