Subroutines and Functions

40
1 Subroutines and Functions Chapter 6 in Deitel, Deitel and Nieto

description

Subroutines and Functions. Chapter 6 in Deitel, Deitel and Nieto. 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) - PowerPoint PPT Presentation

Transcript of Subroutines and Functions

Page 1: Subroutines and Functions

1

Subroutines and Functions

Chapter 6 in Deitel, Deitel and Nieto

Page 2: Subroutines and Functions

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

Page 3: Subroutines and Functions

3

Modules

Modules are one of the “constituent parts” into which a programmer breaks Visual Basic code

Another “unit” of programming is the object

Page 4: Subroutines and Functions

4

Divide and Conquer Example

Page 5: Subroutines and Functions

5

Divide and Conquer Example

Option Explicit

Dim EmployeeName As StringDim Hours As IntegerDim Wage As DoubleDim Salary As Double

Private Sub cmdCalculate_Click() GetInfo CalculateWeeklySalary PrintResultEnd Sub

Problem broken into three modules

They’re getting rid of the currency type so use double

These are “calls”

Page 6: Subroutines and Functions

6

The GetInfo Module

Private Sub GetInfo()

EmployeeName = txtFirstName.Text & _ " " & txtLastName.Text

GetHours

GetWage

End Sub

This module is further broken down into more modules

Page 7: Subroutines and Functions

7

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 IfEnd Sub

Page 8: Subroutines and Functions

8

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 IfEnd Sub

Page 9: Subroutines and Functions

9

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

Page 10: Subroutines and Functions

10

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

Page 11: Subroutines and Functions

11

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

Page 12: Subroutines and Functions

12

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

Page 13: Subroutines and Functions

13

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

Page 14: Subroutines and Functions

14

Page 15: Subroutines and Functions

15

Add Procedure

Does not return anything so sub

Used only by this form so private

Page 16: Subroutines and Functions

16

Add Procedure Result

Or just type this; actually VB supplies the End Sub automatically

Page 17: Subroutines and Functions

17

Calling Subroutines

Private Sub optBlue_Click() Color = vbBlue Call ColorFormEnd Sub

Private Sub optGreen_Click() Color = vbGreen ColorFormEnd Sub

Call ColorForm subroutine using keyword Call

Call ColorForm subroutine without keyword Call

Page 18: Subroutines and Functions

18

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 = ColorEnd Sub

Open parenthesis; close parenthesis

Page 19: Subroutines and Functions

19

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

Page 20: Subroutines and Functions

20

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

Page 21: Subroutines and Functions

21

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 locallyThis 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

Page 22: Subroutines and Functions

22

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

Page 23: Subroutines and Functions

23

Passing a Parameter

Option Explicit

Private Sub Form_Load() Call optRed_ClickEnd Sub

Private Sub optBlue_Click() Call ColorForm(vbBlue)End Sub

Look Ma, no global variables

Passing a parameter

Page 24: Subroutines and Functions

24

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 = ColorEnd Sub

Passed variable and its type

Page 25: Subroutines and Functions

25

What has been gained?

First, the variable color is now local to ColorForm 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 ColorForm, so memory is freed up

Page 26: Subroutines and Functions

26

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)

Page 27: Subroutines and Functions

27

Multiple programmers

Most code is written by teams of codersOne 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

Page 28: Subroutines and Functions

28

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

Page 29: Subroutines and Functions

29

Weekly Salary Revisited

Page 30: Subroutines and Functions

30

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

Page 31: Subroutines and Functions

31

New cmdCalculate_Click (Cont.)

EmployeeName = GetName()

Hours = GetHours()

Debug.Print Hours

Wage = GetWage()

Salary = CalculateWeeklySalary(Hours, Wage)

Call PrintResult(EmployeeName, Salary)

End Sub

Three functions return name, hours and wage respectively, note they are part of assignment statement

CalculateWeeklySalary now a function

Page 32: Subroutines and Functions

32

GetName Function

Private Function GetName() As String

GetName = txtFirstName.Text & " " _

& txtLastName.Text

End Function

Type of thing that gets returned

Whatever you want returned assign to the function’s name

Page 33: Subroutines and Functions

33

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 IfEnd Function

Need to return something even if there was a mistake, better to test on validate method

Page 34: Subroutines and Functions

34

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 IfEnd Function

Page 35: Subroutines and Functions

35

CalculateWeeklySalary Function

Private Function CalculateWeeklySalary(Hours As Integer, _ Wage As Double) As Double

If Hours > 40 Then CalculateWeeklySalary = (Hours - 40) * _

1.5 * Wage + 40 * Wage Else CalculateWeeklySalary = Hours * Wage End IfEnd Function

Page 36: Subroutines and Functions

36

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

Page 37: Subroutines and Functions

37

VB Functions

VB has some built in functions such an Abs(x) - return the absolute value of xExp(x) - return the exponential of x Int(x) - return the integer part of xSgn(x) - return the sign of the number xRnd() - return a “pseudo-random”

number between 0 and 1

Page 38: Subroutines and Functions

38

Random Numbers

Page 39: Subroutines and Functions

39

Random Numbers

Option Explicit

Private Sub cmdRandom_Click() txtRandomSingle.Text = Rnd()End Sub

Private Sub cmdRandomInteger_Click() txtRandomInteger.Text = Int(Rnd() * 10 + 1)End Sub

Page 40: Subroutines and Functions

40

Random numbers

Private Sub Command1_Click()

txtRandomAB.Text = Int(Rnd() * (txtB.Text - txtA.Text + 1) + txtA.Text)

End Sub