IMS 3253: Subroutines 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Procedures Subroutines Parameters –By Value.

Slides:



Advertisements
Similar presentations
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 6- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
Advertisements

Chapter 6, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 6 Sub Procedures And Functions.
Subprograms Functions Procedures. Subprograms A subprogram separates the performance of some task from the rest of the program. Benefits: “Divide and.
Sub and Function Procedures
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Eight Sub and Function Procedures.
1.
Writing General Procedures Often you will encounter programming situations in which multiple procedures perform the same operation This condition can occur.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
VBA Modules, Functions, Variables, and Constants
Example 2.
PSU CS 106 Computing Fundamentals II VB Subprograms & Functions HM 4/29/2008.
Scope of Variables and Constants A Variable or Constant may exist and be Visible for an entire project, for only one form, or for only one procedure Therefore,
5.05 Apply Looping Structures
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
Apply Sub Procedures/Methods and User Defined Functions
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
IE 212: Computational Methods for Industrial Engineering
Chapter 6 Procedures and Functions Instructor: Bindra Shrestha University of Houston – Clear Lake CSCI
CHAPTER SIX Reducing Program Complexity General Sub Procedures and Developer-defined Functions.
Microsoft Visual Basic 2008 CHAPTER 8 Using Procedures and Exception Handling.
1 Web-Enabled Decision Support Systems Objects and Procedures Don McLaughlin IE 423 Design of Decision Support Systems (304)
1 Visual Basic for Applications (VBA) for Excel Prof. Yitzchak Rosenthal.
Why to Create a Procedure
Lecture 8 Visual Basic (2).
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Enhancing the Wage Calculator Application Introducing Function Procedures and.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Fund Raiser Application Introducing Scope, Pass-by-Reference and Option Strict.
VB Procedures. Procedures. Sub procedure: Private/Public Sub SubName(Arguments) … End Sub Private: Can only be accessed by procedures in the same form.
Arrays and 2D Arrays.  A Variable Array stores a set of variables that each have the same name and are all of the same type.  Member/Element – variable.
© 2012 EMC Publishing, LLC Slide 1 Chapter 8 Arrays  Can store many of the same type of data together.  Allows a collection of related values to be stored.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 7 Sub and Function Procedures.
Chapter 6 Sub Procedures
Introduction to VB.NET 2005 Dr. McDaniel IDS4704 Spring 2005.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
© 2006 ITT Educational Services Inc. Introduction to Computer Programming: Unit 10: Chapter 6: Slide 1 Unit 10 Sub Procedures and Functions Chapter 6 Sub.
6c – Function Procedures Lingma Acheson Department of Computer and Information Science, IUPUI CSCI N331 VB.NET Programming.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC PROGRAMMING FUNDAMENTALS Bilal Munir Mughal 1 Chapter-8.
JavaScript, Fourth Edition
PSU CS 106 Computing Fundamentals II VB Declarations HM 5/4/2008.
IMS 4480: Introduction to Web Services 1 Dr. Lawrence West, MIS Dept., University of Central Florida Introduction to Web Services—Topics.
Debugging, Static Variables, ByRef, ByValue Chapt. 6 in Deitel, Deitel and Nieto.
Created by Alia Al-Abdulkarim 2008 Visual Basic Vs. Java.
Week Procedures And Functions 7 A procedure is a collection of statements that performs a task.
Creating Menus Menu Bar – behaves like standard Windows menus Can be used in place of or in addition to buttons to execute a procedure Menu items are controls.
BACS 287 Programming Fundamentals 5. BACS 287 Programming Fundamentals This lecture introduces the following topics: – Procedures Built-in Functions User-defined.
IMS 3253: Forms, Controls, Properties, Events 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Program Elements Assignment.
IMS 3253: Validation and Errors 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Validation and Error Handling Validation.
More on Variables and Subroutines. Introduction Discussion so far has dealt with self- contained subs. Subs can call other subs or functions. A module.
Starting Out with Visual Basic.NET 2 nd Edition Chapter 6 Sub Procedures And Functions.
Object-Oriented Programming: Classes and Objects Chapter 1 1.
Addison Wesley is an imprint of © 2011 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 3 Variables and Calculations.
National Diploma Unit 4 Introduction to Software Development Procedures and Functions.
Visual Basic Declaring Variables Dim x as Integer = 0 In the statement above, x is being declared as an Integer (whole number) and is initialised.
Mr H Kandjimi 2016/01/03Mr Kandjimi1 Week 3 –Modularity in C++
CS0004: Introduction to Programming
Sub Procedures And Functions
Subprograms Functions Procedures.
5.04 Apply Decision Making Structures
A variable is a name for a value stored in memory.
Royal University of Phnom Penh
Object-Oriented Programming: Classes and Objects
Method.
Object-Oriented Programming: Classes and Objects
Chapter 6 Sub Procedures
CIS16 Application Development and Programming using Visual Basic.net
Tonga Institute of Higher Education
Methods.
STARTING OUT WITH Visual Basic 2008
Presentation transcript:

IMS 3253: Subroutines 1 Dr. Lawrence West, MIS Dept., University of Central Florida 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

IMS 3253: Subroutines 2 Dr. Lawrence West, MIS Dept., University of Central Florida 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

IMS 3253: Subroutines 3 Dr. Lawrence West, MIS Dept., University of Central Florida 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

IMS 3253: Subroutines 4 Dr. Lawrence West, MIS Dept., University of Central Florida 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

IMS 3253: Subroutines 5 Dr. Lawrence West, MIS Dept., University of Central Florida 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)

IMS 3253: Subroutines 6 Dr. Lawrence West, MIS Dept., University of Central Florida 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

IMS 3253: Subroutines 7 Dr. Lawrence West, MIS Dept., University of Central Florida 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)

IMS 3253: Subroutines 8 Dr. Lawrence West, MIS Dept., University of Central Florida 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 ( )

IMS 3253: Subroutines 9 Dr. Lawrence West, MIS Dept., University of Central Florida 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

IMS 3253: Subroutines 10 Dr. Lawrence West, MIS Dept., University of Central Florida 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( )

IMS 3253: Subroutines 11 Dr. Lawrence West, MIS Dept., University of Central Florida 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

IMS 3253: Subroutines 12 Dr. Lawrence West, MIS Dept., University of Central Florida 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

IMS 3253: Subroutines 13 Dr. Lawrence West, MIS Dept., University of Central Florida 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

IMS 3253: Subroutines 14 Dr. Lawrence West, MIS Dept., University of Central Florida 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)

IMS 3253: Subroutines 15 Dr. Lawrence West, MIS Dept., University of Central Florida 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)

IMS 3253: Subroutines 16 Dr. Lawrence West, MIS Dept., University of Central Florida 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

IMS 3253: Subroutines 17 Dr. Lawrence West, MIS Dept., University of Central Florida 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

IMS 3253: Subroutines 18 Dr. Lawrence West, MIS Dept., University of Central Florida 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)

IMS 3253: Subroutines 19 Dr. Lawrence West, MIS Dept., University of Central Florida 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)

IMS 3253: Subroutines 20 Dr. Lawrence West, MIS Dept., University of Central Florida 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)

IMS 3253: Subroutines 21 Dr. Lawrence West, MIS Dept., University of Central Florida 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

IMS 3253: Subroutines 22 Dr. Lawrence West, MIS Dept., University of Central Florida 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 = "")

IMS 3253: Subroutines 23 Dr. Lawrence West, MIS Dept., University of Central Florida 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

IMS 3253: Subroutines 24 Dr. Lawrence West, MIS Dept., University of Central Florida 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, " ")

IMS 3253: Subroutines 25 Dr. Lawrence West, MIS Dept., University of Central Florida 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( )

IMS 3253: Subroutines 26 Dr. Lawrence West, MIS Dept., University of Central Florida 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

IMS 3253: Subroutines 27 Dr. Lawrence West, MIS Dept., University of Central Florida 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

IMS 3253: Subroutines 28 Dr. Lawrence West, MIS Dept., University of Central Florida 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