Presentation is loading. Please wait.

Presentation is loading. Please wait.

T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 15 Fund Raiser Application Introducing Scope, Pass-by-Reference and Option Strict.

Similar presentations


Presentation on theme: "T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 15 Fund Raiser Application Introducing Scope, Pass-by-Reference and Option Strict."— Presentation transcript:

1 T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 15 Fund Raiser Application Introducing Scope, Pass-by-Reference and Option Strict

2  2009 Pearson Education, Inc. All rights reserved. 2 Outline 15.1 Test-Driving the Fund Raiser Application 15.2 Constructing the Fund Raiser Application 15.3 Passing Arguments: Pass-by-Value vs. Pass-by-Reference 15.4 Option Strict

3  2009 Pearson Education, Inc. All rights reserved. 3 In this tutorial you will learn: ■Create variables that can be used in all the Form ’ s procedures. ■Pass arguments by reference, using ByRef, so that the called procedure can modify the caller ’ s variables. ■Eliminate subtle data-type errors by enabling Option Strict in your projects. ■Change a value from one data type to another, using methods of class Convert. Objectives

4 Application Requirements  2009 Pearson Education, Inc. All rights reserved. 4 15.1 Test-Driving the Fund Raiser Application An organization is hosting a fund raiser to collect donations. A portion of each donation is used to cover the operating expenses of the organization—the rest of the donation goes to the charity. Create an application that allows the organization to keep track of the total amount of money raised. The application should deduct 17% of each donation for operating costs—the remaining 83% is given to the charity. The application should display the amount of each donation after the 17% for operating expenses is deducted—it also should display the total amount raised for the charity for all donations up to that point.

5  2009 Pearson Education, Inc. All rights reserved. 5 Test-Driving the Fund Raiser Application ■Run the completed application (Fig. 15.1) Figure 15.1 | Fund Raiser application’s Form.

6  2009 Pearson Education, Inc. All rights reserved. 6 Test-Driving the Fund Raiser Application (Cont.) ■The application calculates the amount of the donation after the operating expenses have been deducted and displays the result in the After expenses: field (Fig. 15.2). Figure 15.2 | Fund Raiser application’s Form with first donation entered.

7  2009 Pearson Education, Inc. All rights reserved. 7 Test-Driving the Fund Raiser Application (Cont.) ■Enter more donations, and note that the total raised increases with each additional donation (Fig. 15.3). Figure 15.3 | Making further donations. Total of all donations (minus expenses)

8  2009 Pearson Education, Inc. All rights reserved. 8 When the user changes the current donation amount in the TextBox: Clear Label that displays amount of current donation that goes toward charity When the user clicks the Make Donation Button: Obtain amount of current donation from TextBox Call function CalculateDonation to calculate amount of current donation that goes toward charity (amount after operating costs) Display amount of current donation that goes toward charity Update total amount raised for charity (from all donations received) Display total amount raised for charity When the CalculateDonation procedure gets called: Calculate operating costs (multiply the donated amount by the operating-cost percentage) Calculate amount of donation that goes toward charity (subtract operating costs from donated amount) 15.2 Constructing the Fund Raiser Application

9  2009 Pearson Education, Inc. All rights reserved. 9 ■Now use an ACE table to convert the pseudocode to Visual Basic (Fig. 15.4). Figure 15.4 | Fund Raiser application’s ACE table. (Part 1 of 2.) Action/Control/Event Table for the Fund Raiser Application

10  2009 Pearson Education, Inc. All rights reserved. 10 Figure 15.4 | Fund Raiser application’s ACE table. (Part 2 of 2.) Action/Control/Event Table for the Fund Raiser Application (Cont.)

11  2009 Pearson Education, Inc. All rights reserved. 11 Examining Scope with the Fund Raiser Application ■Open the template application (Fig. 15.5). Figure 15.5 | Fund Raiser template application ’ s Form.

12  2009 Pearson Education, Inc. All rights reserved. 12 Examining Scope with the Fund Raiser Application (Cont.) ■Add lines 2-3 of Fig. 15.6 to FundRaiser.vb. Figure 15.6 | Declaring an instance variable in class FundRaiserForm.

13  2009 Pearson Education, Inc. All rights reserved. 13 ■An instance variable is a variable declared inside a class, but outside any of the class’s procedure definitions. –All procedures in the same class have access to this variable and can modify its value. –Instance variables have module scope. Module scope begins at the identifier after keyword Class and terminates at the End Class statement. Examining Scope with the Fund Raiser Application (Cont.)

14  2009 Pearson Education, Inc. All rights reserved. 14 Examining Scope with the Fund Raiser Application (Cont.) ■Double click the Make Donation Button to generate its Click event handler (Fig. 15.7). Figure 15.7 | Adding a Click event handler to the application.

15  2009 Pearson Education, Inc. All rights reserved. 15 Examining Scope with the Fund Raiser Application (Cont.) ■Add lines 30-31 of Fig. 15.8 to the event handler. Figure 15.8 | Declaring local variables in the donateButton_click event handler. ■Variable donation stores the original donation amount. ■Variable afterCosts stores the donation amount after the operating expenses have been deducted.

16  2009 Pearson Education, Inc. All rights reserved. 16 ■Identifiers that are declared inside a procedure (but outside a control statement) have procedure scope. –Procedure scope begins at the identifier ’ s declaration and ends at the last statement of the procedure. –Identifiers with procedure scope cannot be referenced outside of the procedure in which they are declared. –A procedure ’ s parameters also have procedure scope. ■Identifiers declared inside control statements (such as inside an If...Then statement) have block scope. –Block scope begins at the identifier ’ s declaration and ends at the enclosing block ’ s final statement. Examining Scope with the Fund Raiser Application (Cont.)

17  2009 Pearson Education, Inc. All rights reserved. 17 ■Variables with either procedure scope or block scope are called local variables. –These variables cannot be referenced outside the procedure or block in which they are declared. –If a local variable has the same name as an instance variable, the instance variable is hidden by the local variable. –You can still access the instance variable by preceding its name with the keyword Me and a dot (. ). Examining Scope with the Fund Raiser Application (Cont.)

18  2009 Pearson Education, Inc. All rights reserved. 18 Error-Prevention Tip Hidden variable names can sometimes lead to subtle logic errors. Use unique names for all variables, regardless of scope, to prevent an instance variable from becoming hidden.

19  2009 Pearson Education, Inc. All rights reserved. 19 Examining Scope with the Fund Raiser Application (Cont.) ■The constant COSTS, which stores the operating- cost percentage, is “local” to this procedure (Fig. 15.9) and cannot be used elsewhere. Figure 15.9 | Function procedure CalculateDonation provided in the template application. Parameter donatedAmount has procedure scope because it is declared in the procedure header Local variable netDonation has procedure scope because it is declared in the procedure body

20  2009 Pearson Education, Inc. All rights reserved. 20 ■Replace the constant COSTS with the variable donation, which is declared as a local variable in donate­Button_Click. –Note the jagged line under donation to indicate an error (Fig. 15.10). –Variables with procedure scope can be accessed and modified only in the procedure in which they are defined. Examining Scope with the Fund Raiser Application (Cont.) Figure 15.10 | Demonstrating procedure scope.

21  2009 Pearson Education, Inc. All rights reserved. 21 Examining Scope with the Fund Raiser Application (Cont.) ■This code (Fig. 15.11) obtains the donation amount from the donationTextBox. Figure 15.11 | Obtaining the donation amount.

22  2009 Pearson Education, Inc. All rights reserved. 22 Examining Scope with the Fund Raiser Application (Cont.) ■This code (Fig. 15.12) invokes procedure CalculateDonation with the amount donated. ■The donation amount after operating costs is formatted as a currency string. Figure 15.12 | Calculating and displaying the donation amount after operating expenses.

23  2009 Pearson Education, Inc. All rights reserved. 23 Examining Scope with the Fund Raiser Application (Cont.) ■Add the display code (Fig. 15.13) to the event handler. Figure 15.13 | Updating and displaying the total amount raised for charity.

24  2009 Pearson Education, Inc. All rights reserved. 24 ■Instance variable totalRaised has module scope, and therefore maintains its value between procedure calls. ■Variables with procedure scope, such as donation, do not retain their values between procedure calls. –These must be reinitialized each time their procedure is invoked. Examining Scope with the Fund Raiser Application (Cont.)

25  2009 Pearson Education, Inc. All rights reserved. 25 Examining Scope with the Fund Raiser Application (Cont.) ■When the user enters data into the TextBox, the TextChanged event (Fig. 15.14) occurs and line 23 should clear the previous donation from the After expenses: Label. Figure 15.14 | Clearing the Donation: TextBox.

26  2009 Pearson Education, Inc. All rights reserved. 26 ■The keyword ByVal indicates that an argument will be passed by value. –The application makes a copy of the argument ’ s value and passes the copy to the called procedure. –Changes made to the copy in the called procedure do not affect the original variable ’ s value. ■The keyword ByRef indicates that an argument will be passed by reference. –The original variable in the calling procedure can be accessed and modified directly by the called procedure. –This is useful in some situations, such as when a procedure needs to return more than one result. 15.3 Passing Arguments: Pass-by-Value vs. Pass-by-Reference

27  2009 Pearson Education, Inc. All rights reserved. 27 ■Replace line 37 in the event handler with line 37 of Fig. 15.15. ■Note that the second argument is flagged as a compilation error. Passing Arguments with ByRef in the Fund Raiser Application Figure 15.15 | Passing variable afterCosts by reference.

28  2009 Pearson Education, Inc. All rights reserved. 28 ■Delete the CalculateDonation Function procedure (Fig. 15.16) so it can be rewritten. Figure 15.16 | Function procedure CalculateDonation to be removed. Passing Arguments with ByRef in the Fund Raiser Application (Cont.) Delete these lines of code

29  2009 Pearson Education, Inc. All rights reserved. 29 ■Keyword ByRef (line 7 of Fig. 15.17) indicates that variable netDonation is passed by reference. –Any changes made to variable net­Donation in CalculateDonation affect donateButton_Click ’ s local variable afterCosts. –Since CalculateDonation no longer needs to return a value, CalculateDonation is now created as a Sub procedure. Passing Arguments with ByRef in the Fund Raiser Application (Cont.) Figure 15.17 | CalculateDonation Sub procedure.

30  2009 Pearson Education, Inc. All rights reserved. 30 ■Assigning the calculation result (Fig. 15.18) to variable netDonation actually assigns the value to local variable afterCosts in donateButton_Click. Passing Arguments with ByRef in the Fund Raiser Application (Cont.) Figure 15.18 | Calculating the donation that goes toward charity after operating costs have been deducted.

31  2009 Pearson Education, Inc. All rights reserved. 31 ■Data types in Visual Basic are divided into two categories: –A variable of a value type (such as Integer ) simply contains a value of that type. Dim count As Integer = 7 –A variable of a reference type contains the location where an object is stored in memory. –Reference type instance variables are initialized by default to the value Nothing. –Except for type String, primitive types are value types. 15.3 Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.)

32  2009 Pearson Education, Inc. All rights reserved. 32 ■To interact with an object, you must use a variable that references the object: –to invoke the object ’ s methods –to access the object ’ s properties. currentTimeLabel.Text = String.Format("{0:hh:mm:ss tt}", Date.Now) ■By default, arguments are passed by value. 15.3 Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.)

33  2009 Pearson Education, Inc. All rights reserved. 33 ■When a reference-type variable is passed to a procedure by value, a copy of the object ’ s location is passed. ■In effect, the variable is passed by value, but the object to which the variable refers is passed by reference. ■If you want to change which object a reference- type variable refers to, you could pass that variable to a procedure by reference. 15.3 Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.)

34  2009 Pearson Education, Inc. All rights reserved. 34 ■When a computer accesses data, it needs to know its type in order for the data to make sense. –Imagine you are purchasing a book from an online store that ships internationally. –You notice that the price for the book is 20, but no currency is associated with the price. –If the currency is different from the one that you normally use, you need to perform a conversion to get the price. 15.4 Option Strict

35  2009 Pearson Education, Inc. All rights reserved. 35 ■Similar conversions occur in an application. –Visual Basic can convert one data type to another, as long as the conversion “ makes sense. ” –Assign an Integer value to a Decimal variable is allowed without writing additional code. –These types of assignments perform so-called implicit conversions. –When an attempted conversion does not make sense, such as assigning "hello" to an Integer variable, an error occurs. 15.4 Option Strict (Cont.)

36  2009 Pearson Education, Inc. All rights reserved. 36 ■Figure 15.19 lists some of Visual Basic’s data types and their allowed implicit conversions. Figure 15.19 | Some data types and their allowed implicit conversions. 15.4 Option Strict (Cont.)

37  2009 Pearson Education, Inc. All rights reserved. 37 ■Placing a smaller data type into a larger one is called an implicit widening conversion. ■When a larger type is assigned to a smaller type either a runtime error occurs or the assignment is permitted. Dim value1 As Double = 4.6 Dim value2 As Integer = value1 ■Variable value2 will be assigned 5 — the result of implicit conversion. –Such conversions are called narrowing conversions. –The actual value being assigned may be altered without your being aware of it. 15.4 Option Strict (Cont.)

38  2009 Pearson Education, Inc. All rights reserved. 38 ■Visual Basic provides a project setting called Option Strict. –This setting disallows implicit narrowing conversions. –You can override this by performing narrowing conversions explicitly. 15.4 Option Strict (Cont.)

39  2009 Pearson Education, Inc. All rights reserved. 39 ■Right click the project name in the Solution Explorer. ■Select Properties to open the property pages tab (Fig. 15.20). Figure 15.20 | FundRaiser ’ s property page tab. Enabling Option Strict

40  2009 Pearson Education, Inc. All rights reserved. 40 ■On the left side of the tab, select the Compile category (Fig. 15.21). Figure 15.21 | Selecting Compile in the FundRaiser ’ s property pages. Enabling Option Strict (Cont.) Compile category ComboBox containing value for Option Strict, which is set to Off by default

41  2009 Pearson Education, Inc. All rights reserved. 41 ■Select On in the ComboBox labeled Option Strict: (Fig. 15.22). Figure 15.22 | Setting Option Strict to On. Enabling Option Strict (Cont.) On option for Option Strict

42  2009 Pearson Education, Inc. All rights reserved. 42 ■You can also set Option Strict to On programmatically by adding the following statement as the first line of code in a source-code file: Option Strict On Enabling Option Strict (Cont.)

43  2009 Pearson Education, Inc. All rights reserved. 43 ■Select Tools > Options..., then expand the Projects and Solutions node and select VB Defaults. ■Select On in the ComboBox labeled Option Strict: (Fig. 15.23). Figure 15.23 | Setting default for Option Strict to On. Enabling Option Strict (Cont.)

44  2009 Pearson Education, Inc. All rights reserved. 44 ■When Option Strict is On, you must write code to perform narrowing conversions explicitly. –This helps avoid subtle errors that could result from implicit conversions. –Class Convert (Fig. 15.24) helps you perform conversions when Option Strict is On. 15.4 Option Strict (Cont.) Figure 15.24 | Three of class Convert ’s methods.

45  2009 Pearson Education, Inc. All rights reserved. 45 ■Line 12 in Fig. 15.25 is underlined, indicating that Option Strict prohibits an implicit conversion from Double to Decimal. ■This conversion is not allowed by Option Strict because converting from Double to Decimal could result in data loss. Figure 15.25 | Option Strict prohibits implicit narrowing conversions. Using Class Convert in the Fund Raiser Application

46  2009 Pearson Education, Inc. All rights reserved. 46 ■Method Convert.ToDecimal (Fig. 15.26) converts the Double value to a Decimal value. ■This error also could be corrected by declaring the COSTS constant as a Decimal. Figure 15.26 | Explicitly performing a narrowing conversion with Convert.ToDecimal. Using Class Convert in the Fund Raiser Application (Cont.)

47  2009 Pearson Education, Inc. All rights reserved. 47 ■The error at line 32 (Fig. 15.27) indicates that Option Strict prohibits an implicit conversion from Double to Decimal. Figure 15.27 | Option Strict prohibits a narrowing conversion from type Double to type Decimal. Using Class Convert in the Fund Raiser Application (Cont.)

48  2009 Pearson Education, Inc. All rights reserved. 48 ■Method Convert.ToDecimal explicitly converts donationTextBox.Text to a Decimal. ■After this change is made, the jagged line disappears (Fig. 15.28). Figure 15.28 | Explicitly converting a Double to type Decimal with Convert.ToDecimal. Using Class Convert in the Fund Raiser Application (Cont.) ■Note that each method in class Convert has multiple versions for converting various types to the type specified in the method name.

49  2009 Pearson Education, Inc. All rights reserved. 49 Instance variable declaration Procedure CalculateDonation determines the amount of donation after operating costs— parameter netDonation is modified directly (using ByRef) Converting the calculation result to type Decimal ■Figure 15.29 presents the source code for the Fund Raiser application. Outline (1 of 3 )

50  2009 Pearson Education, Inc. All rights reserved. 50 Convert donation amount from a Double to a Decimal value Outline (2 of 3 )

51  2009 Pearson Education, Inc. All rights reserved. 51 afterCosts is passed by reference Outline (3 of 3 )


Download ppt "T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 15 Fund Raiser Application Introducing Scope, Pass-by-Reference and Option Strict."

Similar presentations


Ads by Google