If Subroutines and Functions Chapter 4 and 5
If, Subroutines and Functions Chapter 4 and 5 in Schneider 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
If-Then Example If State=“PA” Then Price=Price*(1. 06) End If ‘State ‘Recalculates the price factoring in the PA ‘sales tax if the state is PA ‘Note strings are more easily compared in VB 10
Condition A condition is an expression that evaluates to a Boolean value (true or false) It often involves a comparison l l l A>B A >= B A<B A <= B A=B A <> B (is A greater than B? ) (is A greater than or equal to B? ) (is A less than or equal to B? ) (is A not equal to B? ) ‘(does not use !) 11
Compound Conditions Boolean operators can be used to combine conditions And: both expressions must evaluate to true for combination to be true Or: if either expression evaluates to true, the combination is true Not: if an expression evaluates to true, Not(expression) evaluates to false and vice versa 12
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. 13
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 14
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 15
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 16
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 17
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 18
19
Add Procedure Does not return anything so sub Used only by this form so private 20
Add Procedure Result Or just type this; actually VB supplies the End Sub automatically 21
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 22
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 23
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 24
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 25
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 26
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 27
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 28
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 29
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 30
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) 31
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 32
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 33
Weekly Salary Revisited 34
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 35
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 36
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 37
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 38 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 39
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 40
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 41
Else. If If Grade > 94 Then Letter_Grade = “A” Else. If Grade > 86 Then Letter_Grade = “B” Else. If Grade > 78 Then Letter_Grade = “C” Else. If Grade > 70 Then Letter_Grade=“D” Else Letter_Grade=“F” End. If 42
Target Resize Program: Passing a control as an argument 43
Target Resize Program: Passing a control as an argument 44
Target Code Private Sub Form_Load() sha. Circle 1. Tag = 0. 9 sha. Circle 2. Tag = 0. 8 sha. Circle 3. Tag = 0. 7 sha. Circle 4. Tag = 0. 6 sha. Circle 5. Tag = 0. 5 sha. Circle 6. Tag = 0. 4 sha. Circle 7. Tag = 0. 3 sha. Circle 8. Tag = 0. 2 sha. Circle 9. Tag = 0. 1 End Sub 45
Target Code Private Sub Form_Resize() Call Circle. Update(sha. Circle 1) Call Circle. Update(sha. Circle 2) Call Circle. Update(sha. Circle 3) Call Circle. Update(sha. Circle 4) Call Circle. Update(sha. Circle 5) Call Circle. Update(sha. Circle 6) Call Circle. Update(sha. Circle 7) Call Circle. Update(sha. Circle 8) Call Circle. Update(sha. Circle 9) End Sub 46
Target Code Private Sub Circle. Update(My. Circle As Shape) My. Circle. Width = My. Circle. Tag * _ frm. Target. Scale. Width My. Circle. Height = My. Circle. Tag * _ frm. Target. Scale. Height My. Circle. Left = frm. Target. Scale. Width / 2 - _ My. Circle. Width / 2 My. Circle. Top = (frm. Target. Scale. Height - _ My. Circle. Height) 2 End Sub 47
- Slides: 47