T U T O R I A L 2009 Pearson Education, Inc. All rights reserved. 1 13 Enhancing the Wage...

53
T U T O R I A L 2009 Pearson Education, Inc. All rights rese 1 13 Enhancing the Wage Calculator Application Introducing Function Procedures and Sub Procedures

Transcript of T U T O R I A L 2009 Pearson Education, Inc. All rights reserved. 1 13 Enhancing the Wage...

T U T O R I A L

2009 Pearson Education, Inc. All rights reserved.

1

13Enhancing the

Wage Calculator Application

Introducing FunctionProcedures and Sub Procedures

2009 Pearson Education, Inc. All rights reserved.

2

Outline

13.1 Test-Driving the Enhanced Wage Calculator Application

13.2 Classes and Procedures

13.3 Function Procedures

13.4 Using Sub Procedures in the Wage Calculator Application

13.5 Using the Debugger: Debugging Controls

13.6 Optional Parameters

2009 Pearson Education, Inc. All rights reserved.

3

In this tutorial you will learn: ■ Construct applications modularly from pieces

called procedures.■ Work with “built-in” procedures. ■ Distinguish between Function procedures and Sub procedures, and determine when each should be used.

■ Create your own Function proceduresand Sub procedures.

■ Use the Debugging controls on the Standard Toolbar.

Objectives

2009 Pearson Education, Inc. All rights reserved.

4

■ The best way to develop and maintain a large application is to construct it from smaller, more manageable pieces.

– This technique is known as divide and conquer(also called componentization).

■ Manageable pieces include program components—known as procedures.

Introduction

Application Requirements

2009 Pearson Education, Inc. All rights reserved.

513.1 Test-Driving the EnhancedWage Calculator Application

A payroll company calculates the gross earnings per week of employees. Employees’ weekly salaries are based on the number of hours they worked and their hourly wages. Create an application that accepts this information and calculates each employee’s total earnings. The application assumes a standard work week of 40 hours. The wages for 40 or fewer hours are calculated by multiplying the employee’s hourly wage by the number of hours worked. Any time worked over 40 hours in a week is considered “overtime” and earns time and a half. Salary for time and a half is calculated by multiplying the employee’s hourly wage by 1.5 and multiplying the result of that calculation by the number of overtime hours worked. The total overtime earned is added to the user’s gross earnings for the regular 40 hours of work to calculate the total earnings for that week.

2009 Pearson Education, Inc. All rights reserved.

6Test-Driving the Enhanced

Wage Calculator Application

■ Run the completed application (Fig. 13.1).

Figure 13.1 | Wage Calculator running.

■ Click the Calculate Button. The result ($475.00) is displayed in the Gross earnings: Label.

2009 Pearson Education, Inc. All rights reserved.

7

■ The key to creating large applications is tobreak them into smaller pieces.

■ In object-oriented programming, these pieces consist primarily of classes, which can be further broken down into methods.

■ Programmers combine programmer-defined classes and methods with preexisting code inthe .NET Framework Class Library.

– Using preexisting code saves time, effort and money.

– The concept of reusing code increases efficiency for application developers.

13.2 Classes and Procedures

2009 Pearson Education, Inc. All rights reserved.

8

13.2 Classes and Procedures (Cont.)

■ Figure 13.2 explains several pre-existingVisual Basic methods.

Figure 13.2 | Some predefined Visual Basic methods. (Part 1 of 2.)

Procedure Description Example

Math.Max(x, y) Returns the larger value of x and y Math.Max(2.3, 12.7) is 12.7

Math.Max(-2.3, -12.7) is -2.3

Math.Min(x, y) Returns the smaller value of x and y Math.Min(2.3, 12.7) is 2.3

Math.Min(-2.3, -12.7) is -12.7

Math.Sqrt(x) Returns the square root of x Math.Sqrt(9) is 3.0

Math.Sqrt(2) is 1.4142135623731

Pmt(x, y, z) Calculates loan payments where x specifies the interest rate, y specifies the number of payment periods and z specifies the principal value of the loan

Pmt(0.05, 12, -4000) is 451.301640083261

2009 Pearson Education, Inc. All rights reserved.

9

13.2 Classes and Procedures (Cont.)

Procedure Description Example

Val(x) Returns the numeric value of x Val("5") is 5 Val("5a8") is 5 Val("a5") is 0

String.Format (formatString, listOfArguments)

Returns a formatted String. The first parameter, formatString, specifies the formatting and listOfArguments specifies the values to format

String.Format("{0:C}", 1.23) is "$1.23"

Figure 13.2 | Some predefined Visual Basic methods. (Part 2 of 2.)

2009 Pearson Education, Inc. All rights reserved.

10

Creating the Hypotenuse Calculator Application

■ Open HypotenuseCalculator.sln in the HypotenuseCalculator directory (Fig. 13.3).

Figure 13.3 | Hypotenuse Calculator GUI.

2009 Pearson Education, Inc. All rights reserved.

11Creating the Hypotenuse

Calculator Application (Cont.)

■ The event handler for the Calculate Hypotenuse Button is incomplete (Fig. 13.4).

Figure 13.4 | Hypotenuse Calculator template code.

Lengths for sides A, Band hypotenuse

Square of lengths for sidesA, B and hypotenuse

Message dialog displays if negative values (or non-

numeric values) are entered

2009 Pearson Education, Inc. All rights reserved.

12Creating the Hypotenuse

Calculator Application (Cont.)

■ The procedure begins in line 28 (Fig. 13.5) with keyword Function, followed by a procedure name

Figure 13.5 | Hypotenuse Calculator GUI.

Function procedure header

End Function keywords mark the end of a

Function procedure

2009 Pearson Education, Inc. All rights reserved.

13

Software Design Tip

To promote reusability, each procedure should perform a single well-defined task, and the procedure name should express that task effectively and concisely.

2009 Pearson Education, Inc. All rights reserved.

14

Good Programming Practice

Choosing meaningful procedure names and parameter names makes applications more readable and reduces the need for excessive comments.

2009 Pearson Education, Inc. All rights reserved.

15

■ The procedure name is followed by a set of parentheses containing a parameter declaration.

– The declaration in the parentheses is known as the parameter list,

– Variables (called parameters) are declared, enabling a procedure to receive data that helps the procedure perform its task.

– The parameter list can contain zero or more declarations separated by commas.

Creating the HypotenuseCalculator Application (Cont.)

2009 Pearson Education, Inc. All rights reserved.

16

■ A Function procedure returns one value after it performs its task.

■ To specify the return type, the parameter list is followed by the keyword As, which is in turn followed by a data type.

■ The Function procedure ends with the keywords End Function.

Creating the HypotenuseCalculator Application (Cont.)

2009 Pearson Education, Inc. All rights reserved.

17

Good Programming Practice

Procedure names should be verbs and should begin with an uppercase first letter. Each subsequent word in the name should begin with an uppercase first letter. This naming convention is known as Pascal case.

2009 Pearson Education, Inc. All rights reserved.

18Creating the Hypotenuse

Calculator Application (Cont.)

■ The ^ operator (Fig. 13.6) is used to calculate the square of input.

■ A Return statement is used to return this value.

Figure 13.6 | Square procedure definition.

Calculate the squareusing the ^ operator

2009 Pearson Education, Inc. All rights reserved.

19

Good Programming Practice

Placing a blank line between procedure definitions enhances application readability.

2009 Pearson Education, Inc. All rights reserved.

20Creating the Hypotenuse

Calculator Application (Cont.)

■ These lines call Square by using the procedure name followed by a set of parentheses that contain the procedure’s argument (Fig. 13.7).

Figure 13.7 | Invoking procedure Square.

Calling procedure Square

2009 Pearson Education, Inc. All rights reserved.

21Creating the Hypotenuse

Calculator Application (Cont.)

■ Note that typing the opening parenthesis causes the Visual Basic IDE to display a window containing the procedure’s argument names and types (Fig. 13.8).

■ This is the Parameter Info feature of the IDE.

Figure 13.8 | Parameter Info window.

Parameter Info window

2009 Pearson Education, Inc. All rights reserved.

22

Good Programming Practice

Selecting descriptive parameter names makes the information provided by the Parameter Info feature more meaningful.

2009 Pearson Education, Inc. All rights reserved.

23

■ A procedure is invoked by a procedure call.– The procedure call specifies the procedure name and

provides arguments that the called procedure requires to do its job.

– Each argument is assigned to one of the procedure’s parameters when the procedure is called.

– The number of arguments in the call must match the number of parameters in the definition.

– After completing its task, the called procedure returns control to the caller.

Creating the HypotenuseCalculator Application (Cont.)

2009 Pearson Education, Inc. All rights reserved.

24

■ Keyword ByVal indicates that a copy of the argument’s value should be passed to Square.

– Square receives the copy of the value input by the user and stores it in the parameter input.

– When the Return statement in Square is reached, the value to the right of keyword Return is returned to the point in line 23 where Square was called.

– The procedure’s execution completes, and the parameter that was holding the copy of the value is discarded.

– Program control also transfers to this point, and the application continues.

Creating the HypotenuseCalculator Application (Cont.)

2009 Pearson Education, Inc. All rights reserved.

25Creating the Hypotenuse

Calculator Application (Cont.)

■ Line 32 (Fig. 13.9) calls the .NET Framework Class Library method Sqrt of class Math.

Figure 13.9 | Completing the calculateButton_Click event handler.

2009 Pearson Education, Inc. All rights reserved.

26

Error-Prevention Tip

Small procedures are easier to test, debug and understand than large ones.

2009 Pearson Education, Inc. All rights reserved.

27Creating the Hypotenuse

Calculator Application (Cont.)

■ Run and test the application (Fig. 13.10).

Figure 13.10 | Hypotenuse Calculator application running.

2009 Pearson Education, Inc. All rights reserved.

28Creating a Function Procedure

That Returns the Largest of Three Numbers

■ Open Maximum.sln in the Maximum directory (Fig. 13.11).

Figure 13.11 | Maximum application in Design view.

TextBoxes used toinput three values

2009 Pearson Education, Inc. All rights reserved.

29Creating a Function Procedure That

Returns the Largest of Three Numbers (Cont.)

■ Double click the Maximum Button to create an event handler.

■ Note that Maximum has been underlined in blue, because Function procedure Maximum has not yet been defined (Fig. 13.12).

Figure 13.12 | Invoking Function procedure Maximum.

Calling a procedurethat has not yet been

defined is an error

2009 Pearson Education, Inc. All rights reserved.

30

Common Programming Error

Calling a procedure that does not yet exist or misspelling the procedure name in a procedure call results in a compilation error.

2009 Pearson Education, Inc. All rights reserved.

31Creating a Function Procedure That

Returns the Largest of Three Numbers (Cont.)

■ Create the Function procedure Maximum (Fig. 13.13).

Figure 13.13 | Maximum Function procedure.

Empty Function procedure Maximum

2009 Pearson Education, Inc. All rights reserved.

32

■ The maximum is determined by using the Max method of .NET Framework Class Library class Math (Fig. 13.14).

■ The Return statement terminates executionof the procedure and returns the result of finalMaximum.

Creating a Function Procedure ThatReturns the Largest of Three Numbers (Cont.)

Figure 13.14 | Math.Max returns the larger of its two arguments.

Calling Math.Max to determine the maximum of two values

2009 Pearson Education, Inc. All rights reserved.

33Creating a Function Procedure That

Returns the Largest of Three Numbers (Cont.)

■ Run and test the application (Fig. 13.15).

Figure 13.15 | Maximum application running.

2009 Pearson Education, Inc. All rights reserved.

34Creating a Sub Procedure within the

Wage Calculator Application

■ Open WageCalculator2.sln in the WageCalculator2 directory.

■ Double click the Calculate Button to generatean event handler (Fig. 13.16).

Figure 13.16 | calculateButton_Click calls DisplayPay.

Call to DisplayPay

2009 Pearson Education, Inc. All rights reserved.

35

■ Add Sub procedure DisplayPay to your application (lines 18–39 of Fig. 13.17).

■ There is no return type, because Sub procedures do not return values.

■ When control reaches the End Sub statement, control returns to the calling procedure.

Creating a Sub Procedure withinthe Wage Calculator Application (Cont.)

2009 Pearson Education, Inc. All rights reserved.

36Creating a Sub Procedure within

the Wage Calculator Application (Cont.)

Figure 13.17 | Sub procedure DisplayPay definition.

DisplayPay calculates and displays the user’s gross earnings

2009 Pearson Education, Inc. All rights reserved.

37Creating a Function Procedure within

the Wage Calculator Application

■ Note that the return type of the procedure is Boolean (Fig. 13.18)—the value returned by the procedure must be a Boolean.

Figure 13.18 | Function procedure CheckOverTime definition.

CheckOvertime determines ifthe user has worked overtime

2009 Pearson Education, Inc. All rights reserved.

38

Common Programming Error

Failure to return a value from a Function procedure causes the procedure to return the default value for the return-type (0 for numeric types, False for Booleans, Nothing for so-called reference types), often resulting in logic errors.

2009 Pearson Education, Inc. All rights reserved.

39Creating a Function Procedure within the

Wage Calculator Application (Cont.)

■ In Sub procedure DisplayPay, replace the statement on line 26 (Fig. 13.19).

Figure 13.19 | DisplayPay calls Function procedure CheckOvertime.

Call to procedureCheckOvertime

2009 Pearson Education, Inc. All rights reserved.

40

1 Public Class WageCalculatorForm

2 ' handles Calculate Button's Click event

3 Private Sub calculateButton_Click(ByVal sender As System.Object, _

4 ByVal e As System.EventArgs) Handles calculateButton.Click

5

6 ' declare variables

7 Dim userHours As Double

8 Dim wage As Decimal

9

10 ' assign values from user input

11 userHours = Val(hoursTextBox.Text)

12 wage = Val(wageTextBox.Text)

13

14 ' call DisplayPay Sub procedure

15 DisplayPay(userHours, wage)

16 End Sub ' calculateButton_Click

■ Figure 13.20 presents the source codeof the application.

Outline

(1 of 3 )

Call to Sub procedure that calculates and displays wages

2009 Pearson Education, Inc. All rights reserved.

41

17

18 ' calculate and display wages

19 Sub DisplayPay(ByVal hours As Double, ByVal rate As Decimal)

20

21 ' declare variables

22 Dim earnings As Decimal

23 Const HOUR_LIMIT As Integer = 40

24

25 ' determine wage amount

26 If CheckOvertime(hours, HOUR_LIMIT) = False Then

27 ' earnings for regular wages

28 earnings = hours * rate

29 Else

30 ' regular wages for first HOUR_LIMIT hours

31 earnings = HOUR_LIMIT * rate

32

33 ' time and a half for overtime

34 earnings += ((hours - HOUR_LIMIT) * (1.5 * rate))

35 End If

Outline

(2 of 3 )

Call to Function procedure that determines if user has worked overtime

Sub procedure header specifies parameter names and types

2009 Pearson Education, Inc. All rights reserved.

42

36

37 ' display result

38 earningsResultLabel.Text = String.Format("{0:C}", earnings)

39 End Sub ' DisplayPay

40

41 ' determine whether overtime pay has been earned

42 Function CheckOvertime(ByVal total As Double, _

43 ByVal limit As Integer) As Boolean

44

45 If total > limit Then

46 Return True ' return True if over limit

47 Else

48 Return False ' return False otherwise

49 End If

50 End Function ' CheckOvertime

51 End Class ' WageCalculatorForm

Outline

(3 of 3 )

End Sub keywords indicate the end of Sub procedure definition

Function procedure header specifies parameter names and types as well as a return type

End Function keywords indicate the end of Function procedure definition

2009 Pearson Education, Inc. All rights reserved.

43

13.5 Using the Debugger: Debugging Controls

■ These ToolStripButtons (Fig. 13.21) provide convenient access to commands in the Debug menu.

Figure 13.21 | Debugging controls on the Standard toolbar.

Start Debugging Step Into Step Out

Pause execution Stop Debugging Step Over

2009 Pearson Education, Inc. All rights reserved.

44

Using the Debugger: Debugging Controls

■ In the Wage Calculator application, set a breakpointin line 15 (Fig. 13.22).

■ Select Debug > Start Debugging. Enter the value 7.50 in the Hourly wage: TextBox, and enter 35 in the Weekly hours: TextBox. Click the Calculate Button

Figure 13.22 | Setting a breakpoint.

Breakpoint set at a line containing a procedure call

2009 Pearson Education, Inc. All rights reserved.

45

■ The Step Into ToolStripButton ( ) executes the next statement in the application (Fig. 13.23).

– If the next statement to execute is a procedure call, control is transferred to the called procedure.

– The Step Into ToolStripButton allows you to entera procedure and confirm its execution.

Figure 13.23 | Statement calls procedure DisplayPay.

Next statement to executeis a procedure call

Using the Debugger: Debugging Controls (Cont.)

2009 Pearson Education, Inc. All rights reserved.

46

■ Click the Step Into ToolStripButton to enter procedure DisplayPay (Fig. 13.24).

Figure 13.24 | Using the Standard toolbar’s Step Into ToolStripButton.

Control transfers to the procedure definition

Using the Debugger: Debugging Controls (Cont.)

2009 Pearson Education, Inc. All rights reserved.

47

■ Click the Step Over ToolStripButton ( ) to execute the current statement without stepping into it (Fig. 13.25).

Figure 13.25 | Using the Standard toolbar’s Step Over ToolStripButton.

Procedure CheckOverTimeexecutes without stepping intoit when you click the Step Over

ToolStripButton

Using the Debugger: Debugging Controls (Cont.)

2009 Pearson Education, Inc. All rights reserved.

48

■ Click the Step Over ToolStripButton again. – Step Over behaves like the Step Into when the next

statement to execute does not contain a procedure call.

– If the next statement to execute contains a procedure call, the called procedure executes in its entirety, and the yellow arrow advances to the next executable line (Fig. 13.26).

Figure 13.26 | Using the Standard toolbar’s Step Over ToolStripButton again.

Using the Debugger: Debugging Controls (Cont.)

2009 Pearson Education, Inc. All rights reserved.

49

■ Set a breakpoint at the end of procedure DisplayPay in line 39 (Fig. 13.27).

Figure 13.27 | Using the Standard toolbar’s Continue ToolStripButton.

Using the Debugger: Debugging Controls (Cont.)

2009 Pearson Education, Inc. All rights reserved.

50

■ Clicking the Continue ToolStripButton ( ) executes any statements between the next executable statement and the next breakpoint or the end of the current event handler.

■ Click the Stop Debugging ToolStripButton ( ).

Using the Debugger: Debugging Controls (Cont.)

2009 Pearson Education, Inc. All rights reserved.

51

■ When a procedure is invoked repeatedly with the same argument value, you can specify that such a parameter is an Optional parameter.

■ When the argument for an Optional parameter is omitted, the compiler rewrites the procedure call, inserting the default value.

■ There are three rules for using Optionalparameters:

– Each Optional parameter must have a default value. – The default value must be a constant expression.

– All parameters after an Optional parameter must also be Optional parameters.

13.6 Optional Parameters

2009 Pearson Education, Inc. All rights reserved.

52

■ Consider the Function BoxVolume:

Function BoxVolume( Optional ByVal length As Integer = 1, _ Optional ByVal width As Integer = 1, _ Optional ByVal height As Integer = 1 ) As Integer

Return length * width * heightEnd Function ' BoxVolume

■ Each parameter has a default value specified with an = and a literal value (1).

13.6 Optional Parameters (Cont.)

2009 Pearson Education, Inc. All rights reserved.

53

■ You can now invoke Function BoxVolume several different ways:

BoxVolume() ' returns 1; default values used for length, width, height

BoxVolume(10) ' returns 10; default values used for width, heightBoxVolume(10, 20) ' returns 200; default value used for

heightBoxVolume(10, 20, 30) ' returns 6000; no default values

usedBoxVolume(, 20, 30) ' returns 600; default value used for lengthBoxVolume(10, , 30) ' returns 300; default value used for width

■ Comma placeholders are used when an omitted argument is not the last argument in the call.

13.6 Optional Parameters (Cont.)