Presentation is loading. Please wait.

Presentation is loading. Please wait.

If, Subroutines and Functions

Similar presentations


Presentation on theme: "If, Subroutines and Functions"— Presentation transcript:

1 If, Subroutines and Functions
Chapter 4 and 5 in Schneider

2 Resolution Two definitions of “resolution”
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” Break the problem into manageable pieces Solve the pieces Reassemble the pieces into a complete solution

3 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

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

5 Divide and Conquer Example

6 Divide and Conquer Example
Option Explicit Dim EmployeeName As String Dim Hours As Integer Dim Wage As Double Dim Salary As Double Private Sub cmdCalculate_Click() GetInfo CalculateWeeklySalary PrintResult End Sub They’re getting rid of the currency type so use double Problem broken into three modules (top down) These are “calls”

7 The GetInfo Module Private Sub GetInfo()
EmployeeName = txtFirstName.Text & _ " " & txtLastName.Text GetHours GetWage End Sub This module is further broken down into more modules

8 GetHours Module Private Sub GetHours()
If IsNumeric(txtHours.Text) Then Hours = CInt(txtHours.Text) Else MsgBox ("Please enter a number (e.g. 34)” _ & “for the Hours.") txtHours.Text = "" txtHours.SetFocus End If End Sub Built-in function, has string as argument and returns a Boolean

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

10 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

11 Condition A condition is an expression that evaluates to a Boolean value (true or false) It often involves a comparison A > B (is A greater than B?) A >= B (is A greater than or equal to B?) A < B (is A less than B?) A <= B (is A less than or equal to B?) A=B (is A equal to B?) A <> B (is A not equal to B?) ‘(does not use !)

12 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

13 GetWage Module Private Sub GetWage() If IsNumeric(txtWage.Text) Then
Wage = CDbl(txtWage.Text) Else MsgBox ("Please enter a number “ _ & “ (e.g. 7.95) for the Wage.") txtWage.Text = "" txtWage.SetFocus End If End Sub Puts cursor in textbox so it is ready for user to type in.

14 CalculateWeeklySalary Module
Private Sub CalculateWeeklySalary() If Hours > 40 Then Salary = (Hours - 40) * 1.5 * Wage + _ 40 * Wage Else Salary = Hours * Wage End If End Sub

15 PrintResult Module Private Sub PrintResult()
lblSalary.Caption = EmployeeName & _ " earned " lblSalary.Caption = lblSalary.Caption & _ Format$(Salary, "currency") lblSalary.Caption = lblSalary.Caption & _ " the week of " & Date & "." End Sub

16 Code maintenance Modularization makes the code easier to maintain
If the way the data is obtained changes, we need only change the GetInfo module If we alter the overtime rules, we need only change the CalculateWeeklySalary module If we decide to cut an actual check, we need only change the PrintResult module

17 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

18 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

19

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

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

22 Calling Subroutines Private Sub optBlue_Click() Color = vbBlue
Call ColorForm End Sub Private Sub optGreen_Click() Color = vbGreen ColorForm Call ColorForm subroutine using keyword Call Call ColorForm subroutine without keyword Call

23 Subroutine ColorForm Private Sub ColorForm()
frmSelectColor.BackColor = Color optRed.BackColor = Color optBlue.BackColor = Color optGreen.BackColor = Color optYellow.BackColor = Color optCyan.BackColor = Color optMagenta.BackColor = Color End Sub Open parenthesis; close parenthesis

24 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

25 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

26 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

27 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

28 Passing a Parameter Option Explicit Private Sub Form_Load()
Call optRed_Click End Sub Private Sub optBlue_Click() Call ColorForm(vbBlue) Look Ma, no global variables Passing a parameter

29 Local ColorForm Private Sub ColorForm(Color As Long)
frmSelectColor.BackColor = Color optRed.BackColor = Color optBlue.BackColor = Color optGreen.BackColor = Color optYellow.BackColor = Color optCyan.BackColor = Color optMagenta.BackColor = Color End Sub Passed variable and its type

30 What has been gained? First, the variable color is now local to ColorForm 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 ColorForm, so memory is freed up

31 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.” I.e. to prevent “SIDE-EFFECTS” (

32 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

33 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

34 Weekly Salary Revisited

35 New cmdCalculate_Click
Option Explicit Private Sub cmdCalculate_Click() Dim EmployeeName As String Dim Hours As Integer Dim Wage As Double Dim Salary As Double All variables local now

36 New cmdCalculate_Click (Cont.)
Three functions return name, hours and wage respectively, note they are part of assignment statement EmployeeName = GetName() Hours = GetHours() Debug.Print Hours Wage = GetWage() Salary = CalculateWeeklySalary(Hours, Wage) Call PrintResult(EmployeeName, Salary) End Sub CalculateWeeklySalary now a function Debug.Print prints information in the intermediate Window

37 GetName Function Private Function GetName() As String
GetName = txtFirstName.Text & " " _ & txtLastName.Text End Function Whatever you want returned assign to the function’s name Type of thing that gets returned

38 GetHours Function Private Function GetHours() As Integer
If IsNumeric(txtHours.Text) Then GetHours = CInt(txtHours.Text) Else MsgBox ("There was an error in the hours.") txtHours.Text = "" txtHours.SetFocus GetHours = 0 End If End Function Need to return something even if there was a mistake, better to test on validate method

39 GetWage Function Private Function GetWage() As Double
If IsNumeric(txtWage.Text) Then GetWage = CDbl(txtWage.Text) Else MsgBox ("There was an error in the Wage.") txtWage.Text = "" txtWage.SetFocus GetWage = 0 End If End Function

40 CalculateWeeklySalary Function
Private Function CalculateWeeklySalary(Hours _ As Integer, Wage As Double) As Double If Hours > 40 Then CalculateWeeklySalary = (Hours - 40) * _ * Wage + 40 * Wage Else CalculateWeeklySalary = Hours * Wage End If End Function

41 PrintResult Subroutine
Private Sub PrintResult(EmployeeName As _ String, Salary As Double) lblSalary.Caption = EmployeeName & _ " earned " lblSalary.Caption = lblSalary.Caption & _ Format$(Salary, "currency") lblSalary.Caption = lblSalary.Caption & _ " the week of " & Date & "." End Sub

42 ElseIf If Grade > 94 Then Letter_Grade = “A”
ElseIf Grade > 86 Then Letter_Grade = “B” ElseIf Grade > 78 Then Letter_Grade = “C” ElseIf Grade > 70 Then Letter_Grade=“D” Else Letter_Grade=“F” EndIf

43 Target Resize Program: Passing a control as an argument

44 Target Resize Program: Passing a control as an argument

45 Target Code Private Sub Form_Load() shaCircle1.Tag = 0.9
End Sub

46 Target Code Private Sub Form_Resize() Call CircleUpdate(shaCircle1)
End Sub

47 Target Code Private Sub CircleUpdate(MyCircle As Shape)
MyCircle.Width = MyCircle.Tag * _ frmTarget.ScaleWidth MyCircle.Height = MyCircle.Tag * _ frmTarget.ScaleHeight MyCircle.Left = frmTarget.ScaleWidth / 2 - _ MyCircle.Width / 2 MyCircle.Top = (frmTarget.ScaleHeight - _ MyCircle.Height) \ 2 End Sub


Download ppt "If, Subroutines and Functions"

Similar presentations


Ads by Google