Subroutines and Functions Chapter 6 in Deitel Deitel

Subroutines and Functions Chapter 6 in Deitel, Deitel and Nieto 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

Modules are one of the “constituent parts” into which a programmer breaks Visual Basic code Another “unit” of programming is the object 3

Divide and Conquer Example 4

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 5

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 6

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 7

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 8

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 9

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 10

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 11

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 12

Select a Color Revisited 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, we will use a subroutine 13

14

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

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

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 17

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 18

Scope If a variable is declared at the top of the module, it is referred to as global and is available to all of the modules belonging to the form If a variable is declared within a module, it is referred to as local and is available only within that module 19

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

An Example For example the i in For i=1 To n is only needed within the for loop within one module, 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 21

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

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 23

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 24

What has been gained? First, the variable color is now local to Color. Form meaning that the variable color can be used elsewhwere 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 25

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. ” (http: //www. webopedia. com) 26

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 27

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 function return a value (send back some information) to whatever modules called it 28

Weekly Salary Revisited 29

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 30

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 31

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 32

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 33 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 34

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 35

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 36

VB Functions VB has some built in functions such an Abs(x) - return the absolute value of x l Exp(x) - return the exponential of x l Int(x) - return the integer part of x l Sgn(x) - return the sign of the number x l Rnd() - return a “pseudo-random” number between 0 and 1 l 37

Random Numbers 38

Random Numbers Option Explicit Private Sub cmd. Random_Click() txt. Random. Single. Text = Rnd() End Sub Private Sub cmd. Random. Integer_Click() txt. Random. Integer. Text = Int(Rnd() * 10 + 1) End Sub 39

Random numbers Private Sub Command 1_Click() txt. Random. AB. Text = Int(Rnd() * (txt. B. Text txt. A. Text + 1) + txt. A. Text) End Sub 40
- Slides: 40