Subroutines and Functions Chapter 4 in Scheider 1

Subroutines and Functions Chapter 4 in Scheider 1

Resolution Two definitions of “resolution” l l l A solution … of a problem The act … of separating into constituent or elementary parts (Webster’s New Universal Unabridged Dictionary) One of the primary techniques for solving complex problems is “divide and conquer” l l l Break the problem into manageable pieces Solve the pieces Reassemble the pieces into a complete solution 2

Approaching problems Top down: begin with an overall view of the problem and break it down into parts Bottom up: begin with the pieces one believes will be needed to solve the problem, build up from there Middle out: A combination of the above 3

Modules are one of the “constituent parts” into which a programmer breaks Visual Basic code l A form is a module Another “unit” of programming is the object 4

Divide and Conquer Example 5

Divide and Conquer Example Option Explicit Dim Employee. Name As String Dim Hours As Integer Dim Wage As Double They’re getting rid of the Dim Salary As Double currency type so use double Private Sub cmd. Calculate_Click() Get. Info Calculate. Weekly. Salary Print. Result End Sub These are “calls” Problem broken into three modules (top down) 6

The Get. Info Module Private Sub Get. Info() Employee. Name = txt. First. Name. Text & _ " " & txt. Last. Name. Text Get. Hours This module is further broken down into more Get. Wage modules End Sub 7

Get. Hours Module Private Sub Get. Hours() If Is. Numeric(txt. Hours. Text) Then Hours = CInt(txt. Hours. Text) Else Msg. Box ("Please enter a number (e. g. 34)” _ & “for the Hours. ") txt. Hours. Text = "" txt. Hours. Set. Focus End If End Sub Built-in function, has string as argument and returns a Boolean 8

If Then Else If Condition (evaluates to Boolean) Then Statements if condition is true Else Statements if condition is false End If 9

Get. Wage Module Private Sub Get. Wage() If Is. Numeric(txt. Wage. Text) Then Wage = CDbl(txt. Wage. Text) Else Msg. Box ("Please enter a number “ _ & “ (e. g. 7. 95) for the Wage. ") txt. Wage. Text = "" txt. Wage. Set. Focus End If End Sub Puts cursor in textbox so it is ready for user to type in. 10

Calculate. Weekly. Salary Module Private Sub Calculate. Weekly. Salary() If Hours > 40 Then Salary = (Hours - 40) * 1. 5 * Wage + _ 40 * Wage Else Salary = Hours * Wage End If End Sub 11

Print. Result Module Private Sub Print. Result() lbl. Salary. Caption = Employee. Name & _ " earned " lbl. Salary. Caption = lbl. Salary. Caption & _ Format$(Salary, "currency") lbl. Salary. Caption = lbl. Salary. Caption & _ " the week of " & Date & ". " End Sub 12

Code maintenance Modularization makes the code easier to maintain If the way the data is obtained changes, we need only change the Get. Info module l If we alter the overtime rules, we need only change the Calculate. Weekly. Salary module l If we decide to cut an actual check, we need only change the Print. Result module l 13

Reduce Repeated Code Another possible benefit of modules is the reduction of repeated code A given module can be called more than once from more than one location in the code 14

Select a Color Recall we must change the form’s backcolor property as well as the backcolor property of all the optionbuttons, and we must do that in click method of each of the optionbuttons To prevent a lot of repetition of code, we will use a subroutine 15

16

Add Procedure Does not return anything so sub Used only by this form so private 17

Add Procedure Result Or just type this; actually VB supplies the End Sub automatically 18

Calling Subroutines Private Sub opt. Blue_Click() Color = vb. Blue Call Color. Form End Sub Private Sub opt. Green_Click() Color = vb. Green Color. Form End Sub Call Color. Form subroutine using keyword Call Color. Form subroutine without keyword Call 19

Subroutine Color. Form Private Sub Color. Form() frm. Select. Color. Back. Color = Color opt. Red. Back. Color = Color Open parenthesis; opt. Blue. Back. Color = Color close parenthesis opt. Green. Back. Color = Color opt. Yellow. Back. Color = Color opt. Cyan. Back. Color = Color opt. Magenta. Back. Color = Color End Sub 20

Scope If a variable is declared at the top of the module (form), it is referred to as global and is available to all of the procedures belonging to that module (form) If a variable is declared within a procedure (subroutine or function), it is referred to as local and is available only within that procedure 21

What’s the difference? Global variables should be fundamental to the problem and needed by several procedures Local variables are those that are needed in one or two procedures only 22

An Example For example the i used as a counter in a loop For i=1 To n is only needed within the for loop within one procedure, so it should be declared locally This way i cannot be confused with other counters in the problem (even if they are also called i) Duplicate variable names can be a big problem in longer programs, proper use of scope limits the difficulty 23

Passing a Parameter To get local information from one procedure to another, one “passes” the information The information that is passed is placed in the parentheses 24

Passing a Parameter Option Explicit Private Sub Form_Load() Call opt. Red_Click End Sub Private Sub opt. Blue_Click() Call Color. Form(vb. Blue) End Sub Look Ma, no global variables Passing a parameter 25

Local Color. Form Private Sub Color. Form(Color As Long) frm. Select. Color. Back. Color = Color opt. Red. Back. Color = Color Passed opt. Blue. Back. Color = Color variable and opt. Green. Back. Color = Color its type opt. Yellow. Back. Color = Color opt. Cyan. Back. Color = Color opt. Magenta. Back. Color = Color End Sub 26

What has been gained? First, the variable color is now local to Color. Form meaning that the variable color can be used elsewhere in the program without problem Second, the variable color (which corresponds to a memory location) exits only for the duration of Color. Form, so memory is freed up 27

Information Hiding “The process of hiding details of an object or function. Information hiding is a powerful programming technique because it reduces complexity. …. The programmer can then focus on the new object without worrying about the hidden details. ” “Information hiding is also used to prevent programmers from changing --- intentionally or unintentionally -- parts of a program. ” l I. e. to prevent “SIDE-EFFECTS” (http: //www. webopedia. com) 28

Multiple programmers Most code is written by teams of coders One should be able to use a module without detailed knowledge of how it works (its implementation) If a module uses global variables, then someone using module must declare these variables And if two modules use the same global variables, there can be conflicts 29

To and Fro We have seen how to get local information to a module, now we must consider how to get it back VB distinguishes between subroutines and functions; the difference is that functions return a value (send back some information) to whatever subroutine called it 30

Weekly Salary Revisited 31

New cmd. Calculate_Click Option Explicit Private Sub cmd. Calculate_Click() Dim Employee. Name As String Dim Hours As Integer Dim Wage As Double Dim Salary As Double All variables local now 32

New cmd. Calculate_Click (Cont. ) Three functions Employee. Name = Get. Name() return name, hours Hours = Get. Hours() and wage respectively, note they are part of Debug. Print Hours assignment statement Wage = Get. Wage() Salary = Calculate. Weekly. Salary(Hours, Wage) Call Print. Result(Employee. Name, Salary) End Sub Calculate. Weekly. Salary now a function Debug. Print prints information in the intermediate Window 33

Get. Name Function Private Function Get. Name() As String Get. Name = txt. First. Name. Text & " " _ & txt. Last. Name. Text End Function Whatever you want returned assign to the function’s name Type of thing that gets returned 34

Get. Hours Function Private Function Get. Hours() As Integer If Is. Numeric(txt. Hours. Text) Then Get. Hours = CInt(txt. Hours. Text) Else Msg. Box ("There was an error in the hours. ") txt. Hours. Text = "" Need to return txt. Hours. Set. Focus something even if Get. Hours = 0 there was a mistake, better to test on End If validate method 35 End Function

Get. Wage Function Private Function Get. Wage() As Double If Is. Numeric(txt. Wage. Text) Then Get. Wage = CDbl(txt. Wage. Text) Else Msg. Box ("There was an error in the Wage. ") txt. Wage. Text = "" txt. Wage. Set. Focus Get. Wage = 0 End If End Function 36

Calculate. Weekly. Salary Function Private Function Calculate. Weekly. Salary(Hours _ As Integer, Wage As Double) As Double If Hours > 40 Then Calculate. Weekly. Salary = (Hours - 40) * _ 1. 5 * Wage + 40 * Wage Else Calculate. Weekly. Salary = Hours * Wage End If End Function 37

Print. Result Subroutine Private Sub Print. Result(Employee. Name As _ String, Salary As Double) lbl. Salary. Caption = Employee. Name & _ " earned " lbl. Salary. Caption = lbl. Salary. Caption & _ Format$(Salary, "currency") lbl. Salary. Caption = lbl. Salary. Caption & _ " the week of " & Date & ". " End Sub 38
- Slides: 38