Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2009 Pearson Education, Inc. All rights reserved. 1 7 7 Methods: A Deeper Look.

Similar presentations


Presentation on theme: " 2009 Pearson Education, Inc. All rights reserved. 1 7 7 Methods: A Deeper Look."— Presentation transcript:

1  2009 Pearson Education, Inc. All rights reserved. 1 7 7 Methods: A Deeper Look

2  2009 Pearson Education, Inc. All rights reserved. 2 The greatest invention of the nineteenth century was the invention of the method of invention. – Alfred North Whitehead Form ever follows function. – Louis Henri Sullivan Call me Ishmael. – Herman Melville, Moby Dick When you call me that, smile! – Owen Wister

3  2009 Pearson Education, Inc. All rights reserved. 3 O! call back yesterday, bid time return. – William Shakespeare Answer me in one word. – William Shakespeare There is a point at which methods devour themselves. – Frantz Fanon

4  2009 Pearson Education, Inc. All rights reserved. 4 OBJECTIVES In this chapter you will learn:  To construct programs modularly from methods.  That Shared methods are associated with a class rather than a specific instance of the class.  To use common Math methods from the Framework Class Library.  To create new methods.

5  2009 Pearson Education, Inc. All rights reserved. 5 OBJECTIVES  The mechanisms used to pass information between methods.  Simulation techniques that employ random number generation.  How the visibility of identifiers is limited to specific regions of programs.  To write and use recursive methods (methods that call themselves).

6  2009 Pearson Education, Inc. All rights reserved. 6 7.1 Introduction 7.2 Modules, Classes and Methods 7.3 Subroutines: Methods That Do Not Return a Value 7.4 Functions: Methods That Return a Value 7.5 Shared Methods and Class Math 7.6 GradeBook Case Study: Declaring Methods with Multiple Parameters 7.7 Notes on Declaring and Using Methods 7.8 Method Call Stack and Activation Records 7.9 Implicit Argument Conversions 7.10 Option Strict and Data-Type Conversions

7  2009 Pearson Education, Inc. All rights reserved. 7 7.11 Value Types and Reference Types 7.12 Framework Class Library Namespaces 7.13 Passing Arguments: Pass-by-Value vs. Pass-by-Reference 7.14 Scope of Declarations 7.15 Case Study: Random Number Generation 7.16 Case Study: A Game of Chance 7.17 Method Overloading 7.18 Optional Parameters 7.19 Recursion 7.20 (Optional) Software Engineering Case Study: Identifying Class Operations in the ATM System

8  2009 Pearson Education, Inc. All rights reserved. 8 Programs consist of many pieces, including modules and classes. Modules and classes are composed of methods, fields and properties. You combine new modules and classes with those available in class libraries. Related classes are grouped into namespaces. 7.2 Modules, Classes and Methods

9  2009 Pearson Education, Inc. All rights reserved. 9 Software Engineering Observation 7.1 When possible, use.NET Framework classes and methods instead of writing new classes and methods. This reduces program development time and can prevent the introduction of errors. Performance Tip 7.1.NET Framework Class Library methods are written to perform efficiently. 7.2 Modules, Classes and Methods (Cont.)

10  2009 Pearson Education, Inc. All rights reserved. 10 7.2 Modules, Classes and Methods (Cont.) A method is invoked by a method call. – The method call specifies the method name and provides information. – When the method completes its task, it returns control to the caller. In some cases, the method also returns a result to the caller.

11  2009 Pearson Education, Inc. All rights reserved. 11 7.2 Modules, Classes and Methods (Cont.) Fig. 7.1 | Hierarchical boss-method/worker-method relationship. A boss (the caller) asks a worker (the callee) to perform a task and return the results when the task is done. The worker might call other workers—the boss would be unaware of this (Fig. 7.1).

12  2009 Pearson Education, Inc. All rights reserved. 12 7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7.2 To promote reusability, the capabilities of each method should be limited to the performance of a single, well-defined task, and the name of the method should express that task effectively. Software Engineering Observation 7.3 If you cannot choose a concise method name that expresses the task performed by a method, the method could be attempting to perform too many diverse tasks. Consider dividing such a method into several smaller methods.

13  2009 Pearson Education, Inc. All rights reserved. 13 Outline Payment.vb (1 of 2 ) Subroutines (such as Console.WriteLine ) do not return a value. The console application in Fig. 7.2 uses a subroutine to print a worker’s payment information. Main makes four calls to the subroutine PrintPay. Fig. 7.2 | Subroutine for printing payment information. (Part 1 of 2.)

14  2009 Pearson Education, Inc. All rights reserved. 14 Outline Payment.vb (2 of 2 ) Method PrintPay is a subroutine. Fig. 7.2 | Subroutine for printing payment information. (Part 2 of 2.)

15  2009 Pearson Education, Inc. All rights reserved. 15 7.3 Subroutines: Methods That Do Not Return a Value (Cont.) The format of a subroutine declaration is: Sub method-name(parameter-list) declarations and statements End Sub The parameter-list is a comma-separated list of each parameter’s type and name. – The type of each argument must be consistent with its corresponding parameter’s type. – If a method does not receive any values, the method name is followed by an empty set of parentheses.

16  2009 Pearson Education, Inc. All rights reserved. 16 Common Programming Error 7.1 Declaring a variable in the method’s body with the same name as a parameter variable in the method header is a compilation error. Error-Prevention Tip 7.1 Although it is allowable, an argument passed to a method should not have the same name as the corresponding parameter name in the method declaration. This prevents ambiguity that could lead to logic errors. 7.3 Subroutines: Methods That Do Not Return a Value (Cont.)

17  2009 Pearson Education, Inc. All rights reserved. 17 Software Engineering Observation 7.4 Method names tend to be verbs because methods typically perform actions. By convention, method names begin with an uppercase first letter. For example, a method that sends an e-mail message might be named SendMail. 7.3 Subroutines: Methods That Do Not Return a Value (Cont.) The method body (also referred to as a block) contains declarations and statements. The body of a method declared with Sub must be terminated with End Sub.

18  2009 Pearson Education, Inc. All rights reserved. 18 Error-Prevention Tip 7.2 Small methods are easier to test, debug and understand than large methods. Good Programming Practice 7.1 When a parameter is declared without a type, its type is assumed to be Object. Explicitly declaring a parameter’s type improves program clarity. 7.3 Subroutines: Methods That Do Not Return a Value (Cont.)

19  2009 Pearson Education, Inc. All rights reserved. 19 Outline SquareInteger.vb (1 of 2 ) Functions are methods that return a value to the caller. The console application in Fig. 7.3 uses the function Square to calculate the squares of the integers from 1–10. The For…Next statement displays the results of squaring the integers. Fig. 7.3 | Function for squaring an integer. (Part 1 of 2.)

20  2009 Pearson Education, Inc. All rights reserved. 20 Outline SquareInteger.vb (2 of 2 ) Square receives a copy of counter ’s value. The Return statement terminates the method and returns the result. Fig. 7.3 | Function for squaring an integer. (Part 2 of 2.)

21  2009 Pearson Education, Inc. All rights reserved. 21 7.4 Functions: Methods That Return a Value (Cont.) The Return statement terminates the method and returns the result. The return statement can occur anywhere in a function body. Return expression The return-type indicates the type of the result returned from the function.

22  2009 Pearson Education, Inc. All rights reserved. 22 7.4 Functions: Methods That Return a Value (Cont.) Common Programming Error 7.2 If the expression in a Return statement cannot be converted to the function’s return-type, a run­time error is generated. Common Programming Error 7.3 Failure to return a value from a function (e.g., by forgetting to provide a Return statement) causes the function to return the default value for the return-type, possibly producing incorrect output.

23  2009 Pearson Education, Inc. All rights reserved. 23 7.5 Shared Methods and Class Math A method which performs a task that does not depend on an object is known as a Shared method. – Place the Shared modifier before the keyword Sub or Function. To call a Shared method: ClassName.MethodName(arguments) Class Math provides a collection of Shared methods: Math.Sqrt(900.0)

24  2009 Pearson Education, Inc. All rights reserved. 24 7.5 Shared Methods and Class Math (Cont.) Software Engineering Observation 7.5 It is not necessary to add an assembly reference to use the Math class methods in a program, because class Math is located in the assembly mscorlib.dll, which is referenced by every.NET application. Also it is not necessary to import class Math ’s namespace ( System ), because it is implicitly imported in all.NET applications.

25  2009 Pearson Education, Inc. All rights reserved. 25 Figure 7.4 summarizes several Math class methods. In the figure, x and y are of type Double. Fig. 7.4 | Math class methods. (Part 1 of 3.) 7.5 Shared Methods and Class Math (Cont.)

26  2009 Pearson Education, Inc. All rights reserved. 26 7.5 Shared Methods and Class Math (Cont.) Fig. 7.4 | Math class methods. (Part 2 of 3.)

27  2009 Pearson Education, Inc. All rights reserved. 27 7.5 Shared Methods and Class Math (Cont.) Fig. 7.4 | Math class methods. (Part 3 of 3.)

28  2009 Pearson Education, Inc. All rights reserved. 28 7.5 Shared Methods and Class Math (Cont.) Math.PI and Math.E are declared in class Math with the modifiers Public and Const. – Const declares a constant—a value that cannot be changed. – Constants are implicitly Shared.

29  2009 Pearson Education, Inc. All rights reserved. 29 Outline GradeBook.vb (1 of 5 ) The application in Figs. 7.5–7.6 uses a user-declared method called Maximum to determine the largest of three Integer values. Fig. 7.5 | User-declared method Maximum that has three Integer parameters. (Part 1 of 5.)

30  2009 Pearson Education, Inc. All rights reserved. 30 Outline GradeBook.vb (2 of 5 ) Fig. 7.5 | User-declared method Maximum that has three Integer parameters. (Part 2 of 5.)

31  2009 Pearson Education, Inc. All rights reserved. 31 Outline GradeBook.vb (3 of 5 ) Fig. 7.5 | User-declared method Maximum that has three Integer parameters. (Part 3 of 5.)

32  2009 Pearson Education, Inc. All rights reserved. 32 Outline GradeBook.vb (4 of 5 ) Fig. 7.5 | User-declared method Maximum that has three Integer parameters. (Part 4 of 5.)

33  2009 Pearson Education, Inc. All rights reserved. 33 Outline GradeBook.vb (5 of 5 ) Fig. 7.5 | User-declared method Maximum that has three Integer parameters. (Part 5 of 5.)

34  2009 Pearson Education, Inc. All rights reserved. 34 Outline GradeBookTest.vb (1 of 2 ) Fig. 7.6 | Application to test class GradeBook ’s Maximum method. (Part 1 of 2.)

35  2009 Pearson Education, Inc. All rights reserved. 35 Outline GradeBookTest.vb (2 of 2 ) Fig. 7.6 | Application to test class GradeBook ’s Maximum method. (Part 2 of 2.)

36  2009 Pearson Education, Inc. All rights reserved. 36 There are three ways to call a method: – Using a method name by itself within the same class or module. – Using a reference to an object, followed by a dot (. ) and the method name to call a method of the object. – Using the class or module name and a dot (. ) to call a Shared method. A Shared method can call only other Shared methods. 7.7 Notes on Declaring and Using Methods

37  2009 Pearson Education, Inc. All rights reserved. 37 Common Programming Error 7.4 Declaring a method outside the body of a class or module declaration or inside the body of another method is a syntax error. Common Programming Error 7.5 Omitting the return-value-type in a method declaration, if that method is a function, is a syntax error. Common Programming Error 7.6 Redeclaring a method parameter as a local variable in the method’s body is a compilation error. Common Programming Error 7.7 Returning a value from a method that is a subroutine is a compilation error. 7.7 Notes on Declaring and Using Methods (Cont.)

38  2009 Pearson Education, Inc. All rights reserved. 38 7.8 Method Call Stack and Activation Records A data structure known as a stack is analogous to a pile of dishes. – When a dish is placed on the pile, it is placed at the top (pushing onto the stack). – When a dish is removed from the pile, it is removed from the top (popping off the stack). – Stacks are known as last-in, first-out (LIFO) data structures.

39  2009 Pearson Education, Inc. All rights reserved. 39 7.8 Method Call Stack and Activation Records (Cont.) When a program calls a method, the return address of the caller is pushed onto the method call stack. Successive return addresses are pushed onto the stack. The memory for the local variables in each method is in the activation record or stack frame. When the method returns to its caller, the activation record is popped off the stack. If too many method calls occur then stack overflow occurs.

40  2009 Pearson Education, Inc. All rights reserved. 40 7.9 Implicit Argument Conversions An important feature of argument passing is implicit argument conversion. – A widening conversion occurs when an argument is converted to another type that can hold more data. – A narrowing conversion occurs when there is potential for data loss during the conversion.

41  2009 Pearson Education, Inc. All rights reserved. 41 7.9 Implicit Argument Conversions (Cont.) Figure 7.7 lists the widening conversions supported by Visual Basic. Fig. 7.7 | Widening conversions between primitive types. (Part 1 of 2.)

42  2009 Pearson Education, Inc. All rights reserved. 42 7.9 Implicit Argument Conversions (Cont.) Fig. 7.7 | Widening conversions between primitive types. (Part 2 of 2.)

43  2009 Pearson Education, Inc. All rights reserved. 43 7.9 Implicit Argument Conversions (Cont.) Common Programming Error 7.8 Converting a primitive-type value to a value of another primitive type may change the value if the conversion is not a widening conversion. For example, converting a floating-point value to an integral value truncates any fractional part of the floating-point value (e.g., 4.7 becomes 4).

44  2009 Pearson Education, Inc. All rights reserved. 44 7.9 Implicit Argument Conversions (Cont.) Conversions occur in expressions containing two or more types. Temporary copies of the values are converted to the “widest” type in the expression. The value of integerNumber is converted to type Single for this operation: singleNumber + integerNumber

45  2009 Pearson Education, Inc. All rights reserved. 45 7.10 Option Strict and Data-Type Conversions Option Explicit forces an explicit declaration of variables before they are used. To set Option Explicit to Off, double click My Project in Solution Explorer (Fig. 7.8). Click the Compile tab, then select the value Off from the Option Explicit drop-down list. Fig. 7.8 | Modifying Option Strict and Option Explicit. Compile tab Drop-down list to modify Option Explicit Drop-down list to modify Option Strict Drop-down list to modify Option Infer

46  2009 Pearson Education, Inc. All rights reserved. 46 7.10 Option Strict and Data-Type Conversions (Cont.) Option Strict requires explicit conversion for all narrowing conversions. An explicit conversion uses a cast operator or a method. The methods of class Convert explicitly convert data from one type to another: number = Convert.ToDouble(Console.ReadLine())

47  2009 Pearson Education, Inc. All rights reserved. 47 7.10 Option Strict and Data-Type Conversions (Cont.) Option Infer enables the compiler to infer a variable ’ s type based on its initializer value. You can set the default values of Option Explicit, Option Strict and Option Infer. – Select Tools > Options... – Under Projects and Solutions, select VB Defaults – Choose the appropriate value in each option ’ s ComboBox. Error-Prevention Tip 7.3 From this point forward, all code examples have Option Strict set to On.

48  2009 Pearson Education, Inc. All rights reserved. 48 7.11 Value Types and Reference Types All Visual Basic types can be categorized as either value types or reference types. – A variable of a value type contains data of that type. – A variable of a reference type contains the address of the location in memory where the data is stored.

49  2009 Pearson Education, Inc. All rights reserved. 49 7.11 Value Types and Reference Types (Cont.) Fig. 7.9 | Primitive types. (Part 1 of 3.)

50  2009 Pearson Education, Inc. All rights reserved. 50 7.11 Value Types and Reference Types (Cont.) Fig. 7.9 | Primitive types. (Part 2 of 3.)

51  2009 Pearson Education, Inc. All rights reserved. 51 7.11 Value Types and Reference Types (Cont.) Fig. 7.9 | Primitive types. (Part 3 of 3.)

52  2009 Pearson Education, Inc. All rights reserved. 52 7.12 Framework Class Library Namespaces The.NET framework contains many classes grouped into over 100 namespaces. A program includes the an Imports declaration to use classes from that namespace: Imports System.Windows.Forms

53  2009 Pearson Education, Inc. All rights reserved. 53 7.12 Framework Class Library Namespaces (Cont.) Some key namespaces are described in Fig. 7.10. Fig. 7.10 |.NET Framework Class Library namespaces (a subset). (Part 1 of 2.)

54  2009 Pearson Education, Inc. All rights reserved. 54 7.12 Framework Class Library Namespaces (Cont.) Fig. 7.10 |.NET Framework Class Library namespaces (a subset). (Part 2 of 2.)

55  2009 Pearson Education, Inc. All rights reserved. 55 7.12 Framework Class Library Namespaces (Cont.) Good Programming Practice 7.2 The Visual Studio.NET documentation is easy to search and provides many details about each class. As you learn a class in this book, you should read about the class in the online documentation.

56  2009 Pearson Education, Inc. All rights reserved. 56 7.13 Passing Arguments: Pass-by-Value vs. Pass-by-Reference Arguments are passed pass-by-value or pass-by-reference. – When an argument is passed by value, the program makes a copy of the argument’s value and passes the copy. Changes to the copy do not affect the original variable. – When an argument is passed by reference, the original data can be accessed and modified directly.

57  2009 Pearson Education, Inc. All rights reserved. 57 Outline ByRefTest.vb (1 of 4 ) Figure 7.11 demonstrates passing arguments by value and by reference. Fig. 7.11 | ByVal and ByRef used to pass value-type arguments. (Part 1 of 4.)

58  2009 Pearson Education, Inc. All rights reserved. 58 Outline Squaring number2 by reference. ByRefTest.vb (2 of 4 ) The inner set of parentheses evaluates number3 to its value and passes this value. Squaring number1 by value. Fig. 7.11 | ByVal and ByRef used to pass value-type arguments. (Part 2 of 4.)

59  2009 Pearson Education, Inc. All rights reserved. 59 Outline ByVal indicates that its argument is passed by value. Squaring the number parameter value. ByRef receives its parameter by reference. Squaring the number parameter’s reference. ByRefTest.vb (3 of 4 ) Fig. 7.11 | ByVal and ByRef used to pass value-type arguments. (Part 3 of 4.)

60  2009 Pearson Education, Inc. All rights reserved. 60 Outline ByRefTest.vb (4 of 4) Fig. 7.11 | ByVal and ByRef used to pass value-type arguments. (Part 4 of 4.)

61  2009 Pearson Education, Inc. All rights reserved. 61 Outline ByRefTest.vb (5 of 5 ) Error-Prevention Tip 7.4 When passing arguments by value, changes to the called method’s copy do not affect the original variable’s value. This prevents possible side effects that could hinder the development of correct and reliable software systems. Always pass value-type arguments by value unless you explicitly intend for the called method to modify the caller’s data.

62  2009 Pearson Education, Inc. All rights reserved. 62 7.14 Scope of Declarations A declaration’s scope is the portion of the program that can refer to the declared entity by its name without qualification. The basic scopes are: – Block scope—from the point of the declaration to the end of the block – Method scope—from the point of the declaration to the end of that method – Module scope—the entire body of the class or module. – Namespace scope—accessible to all other elements in the same namespace

63  2009 Pearson Education, Inc. All rights reserved. 63 7.14 Scope of Declarations (cont.) If a local variable has the same name as a field of the class, the field is hidden—this is called shadowing. A variable’s lifetime is the period during which the variable exists in memory. – Variables normally exist as long as their container exists. Error-Prevention Tip 7.5 Use different names for fields and local variables to help prevent subtle logic errors that occur when a method is called and a local variable of the method shadows a field of the same name in the class.

64  2009 Pearson Education, Inc. All rights reserved. 64 Outline Scope.vb (1 of 2 ) This instance variable is shadowed by any local variable named x. Method Begin declares a local variable x Fig. 7.12 | Scoping rules in a class. (Part 1 of 2.)

65  2009 Pearson Education, Inc. All rights reserved. 65 Outline Subroutine UseLocalVariable declares a local variable x Modifying the local variable x UseInstanceVariable does not declare local variables, so x refers to the instance variable. Scope.vb (2 of 2 ) Fig. 7.12 | Scoping rules in a class. (Part 2 of 2.)

66  2009 Pearson Education, Inc. All rights reserved. 66 Outline ScopeTest.vb Fig. 7.13 | Module to test class Scope.

67  2009 Pearson Education, Inc. All rights reserved. 67 7.15 Case Study: Random Number Generation The element of chance can be introduced through class Random. Dim randomObject As New Random() Dim randomNumber As Integer = randomObject.Next() Next generates a positive Integer between zero and Int32.MaxValue. The values returned by Next are actually pseudo-random numbers. The default seed value is based on the current time.

68  2009 Pearson Education, Inc. All rights reserved. 68 7.15 Case Study: Random Number Generation (Cont.) We can produce integers in the range 1–6 by passing an argument to method Next : value = 1 + randomObject.Next(6) The number 6 is the scaling factor. We shift the range of numbers produced by adding 1. Simplify the process by passing two arguments to Next : value = randomObject.Next(1, 7)

69  2009 Pearson Education, Inc. All rights reserved. 69 Outline RandomInteger.vb Figure 7.14 demonstrates the use of class Random and method Next by simulating 20 rolls of a six-sided die. Random numbers are generated by an object of class Random. The values that are produced are in the range from 1 to 6, inclusive. Fig. 7.14 | Random integers from 1 to 6 created by calling Random method Next.

70  2009 Pearson Education, Inc. All rights reserved. 70 Outline RollDice.vb (1 of 2 ) Initializing a Random object. Fig. 7.15 | Demonstrating four die rolls with graphical output. (Part 1 of 2.)

71  2009 Pearson Education, Inc. All rights reserved. 71 Outline The values that are produced are in the range from 1 to 6, inclusive. CType performs conversion from Object to Image. Retrieving the picture from My.Resources. RollDice.vb (2 of 2 ) a)b) Fig. 7.15 | Demonstrating four die rolls with graphical output. (Part 2 of 2.)

72  2009 Pearson Education, Inc. All rights reserved. 72 7.15 Case Study: Random Number Generation (cont.) The Button control can be simply dragged and dropped onto the Form from the Toolbox. – Name the control rollButton and set its Text to Roll. Double click the Button to create the Click event handler. – Note that the event handler is a Sub procedure.

73  2009 Pearson Education, Inc. All rights reserved. 73 7.15 Case Study: Random Number Generation (cont.) The event handler calls method DisplayDie once for each PictureBox. Calling DisplayDie causes dice to appear as if they are being rolled. The images are embedded with the project as resources.

74  2009 Pearson Education, Inc. All rights reserved. 74 7.15 Case Study: Random Number Generation (cont.) – Double click My Project in the Solution Explorer. – Click the Resources tab, then click the down arrow next to the Add Resource button (Fig. 7.16) to select Add Existing File... – Locate the resources you wish to add and click the Open button. – Save your project.

75  2009 Pearson Education, Inc. All rights reserved. 75 7.15 Case Study: Random Number Generation (cont.) Fig. 7.16 | Images added as resources.

76  2009 Pearson Education, Inc. All rights reserved. 76 7.15 Case Study: Random Number Generation (cont.) To access the project ’ s resources, use the method My.Resources.ResourceManager. GetObject. You must convert this Object to type Image to assign it to the PictureBox ’ s Image property; Visual Basic ’ s CType function converts its first argument to the type specified in its second argument.

77  2009 Pearson Education, Inc. All rights reserved. 77 Outline RollTwelveDice.vb (1 of 5 ) Initializing a Random object. Fig. 7.17 | Random class used to simulate rolling 12 six-sided dice. (Part 1 of 5.)

78  2009 Pearson Education, Inc. All rights reserved. 78 Outline Using String.Format to print percentages to two decimal places. RollTwelveDice.vb (2 of 5 ) Fig. 7.17 | Random class used to simulate rolling 12 six-sided dice. (Part 2 of 5.)

79  2009 Pearson Education, Inc. All rights reserved. 79 Outline CType performs conversion from Object to Image. Retrieving the picture from My.Resources. Using String.Format to print percentages to two decimal places. RollTwelveDice.vb (3 of 5 ) Fig. 7.17 | Random class used to simulate rolling 12 six-sided dice. (Part 3 of 5.)

80  2009 Pearson Education, Inc. All rights reserved. 80 Outline RollTwelveDice.vb (4 of 5 ) Fig. 7.17 | Random class used to simulate rolling 12 six-sided dice. (Part 4 of 5.)

81  2009 Pearson Education, Inc. All rights reserved. 81 Outline RollTwelveDice.vb (5 of 5 ) a) b) displayTextBox Fig. 7.17 | Random class used to simulate rolling 12 six-sided dice. (Part 5 of 5.)

82  2009 Pearson Education, Inc. All rights reserved. 82 7.15 Case Study: Random Number Generation (cont.) The TextBox control can be used both for displaying and inputting data. – The data in the TextBox can be accessed via the Text property. – This TextBox ’ s name is displayTextBox and the font size has been set to 9. – The Multiline property has been set to True.

83  2009 Pearson Education, Inc. All rights reserved. 83 7.16 Case Study: A Game of Chance One of the most popular games of chance is a dice game known as “craps": A player rolls two dice. After the dice have come to rest, the sum of the spots on the two upward faces is calculated. If the sum is 7 or 11 on the first throw, the player wins. If the sum is 2, 3 or 12 on the first throw (called “craps”), the player loses. If the sum is 4, 5, 6, 8, 9 or 10 on the first throw, that sum becomes the player’s “point.” To win, players must continue rolling the dice until they “make their point” (i.e., roll their point value). The player loses by rolling a 7 before making the point.

84  2009 Pearson Education, Inc. All rights reserved. 84 Outline CrapsGame.vb (1 of 7 ) The application in Fig. 7.18 simulates the game of craps. Declaring constants through an enumeration. Fig. 7.18 | Craps game using class Random. (Part 1 of 7.)

85  2009 Pearson Education, Inc. All rights reserved. 85 Outline CrapsGame.vb (2 of 7 ) Setting the Image to Nothing causes a PictureBox to appear blank String.Empty represents a string with no characters (""). The Select Case statement analyzes the roll. Fig. 7.18 | Craps game using class Random. (Part 2 of 7.)

86  2009 Pearson Education, Inc. All rights reserved. 86 Outline CrapsGame.vb (3 of 7 ) Fig. 7.18 | Craps game using class Random. (Part 3 of 7.)

87  2009 Pearson Education, Inc. All rights reserved. 87 Outline CrapsGame.vb (4 of 7 ) Determining if a losing roll is made. Fig. 7.18 | Craps game using class Random. (Part 4 of 7.)

88  2009 Pearson Education, Inc. All rights reserved. 88 Outline CrapsGame.vb (5 of 7 ) Fig. 7.18 | Craps game using class Random. (Part 5 of 7.)

89  2009 Pearson Education, Inc. All rights reserved. 89 Outline CrapsGame.vb (6 of 7 ) a) b) rollButtonplayButtonpointGroupBox Fig. 7.18 | Craps game using class Random. (Part 6 of 7.)

90  2009 Pearson Education, Inc. All rights reserved. 90 Outline CrapsGame.vb (7 of 7 ) c) d) Fig. 7.18 | Craps game using class Random. (Part 7 of 7.)

91  2009 Pearson Education, Inc. All rights reserved. 91 String.Empty represents a string with no characters (""). Setting the Image to Nothing causes a PictureBox to appear blank. 7.16 Case Study: A Game of Chance (Cont.)

92  2009 Pearson Education, Inc. All rights reserved. 92 The GroupBox control is a container used to group related controls. – Within the GroupBox pointDiceGroup, we add two PictureBox es. – To add controls to a GroupBox, drag and drop the controls onto it. – We set the GroupBox ’s Text property to Point. 7.16 Case Study: A Game of Chance (Cont.)

93  2009 Pearson Education, Inc. All rights reserved. 93 Enum erations enhance program readability by providing descriptive identifiers for constant numbers or String s. In this application, we created an Enum eration for the various dice combinations. Button s are enabled and disabled with the Enabled property. 7.16 Case Study: A Game of Chance (Cont.)

94  2009 Pearson Education, Inc. All rights reserved. 94 Outline Overload.vb (1 of 2 ) Method overloading allows you to create methods with the same name but different parameters. Figure 7.19 uses overloaded method Square to calculate the square of both an Integer and a Double. Fig. 7.19 | Using overloaded methods. (Part 1 of 2.)

95  2009 Pearson Education, Inc. All rights reserved. 95 Outline Overload.vb (2 of 2 ) Good Programming Practice 7.3 Overloading methods that perform closely related tasks can make programs clearer. Fig. 7.19 | Using overloaded methods. (Part 2 of 2.)

96  2009 Pearson Education, Inc. All rights reserved. 96 Overload resolution determines which method to call. – This process first finds methods that could be used. – Visual Basic converts variables as necessary when they are passed as arguments. – The compiler selects the closest match. 7.17 Method Overloading (Cont.)

97  2009 Pearson Education, Inc. All rights reserved. 97 Outline Overload2.vb (1 of 2 ) The program in Fig. 7.20 illustrates the syntax error that is generated when two methods have the same signature and different return types. Fig. 7.20 | Syntax error generated from overloaded methods with identical parameter lists and different return types. (Part 1 of 2.)

98  2009 Pearson Education, Inc. All rights reserved. 98 Outline Overload2.vb (2 of 2 ) Common Programming Error 7.9 Creating overloaded methods with identical parameter lists and different return types is a compilation error. Fig. 7.20 | Syntax error generated from overloaded methods with identical parameter lists and different return types. (Part 2 of 2.)

99  2009 Pearson Education, Inc. All rights reserved. 99 Optional parameters specify a default value that is assigned to the parameter if that argument is not passed. Sub ExampleMethod(ByVal value1 As Boolean, _ Optional ByVal value2 As Integer = 0) Both of these calls to ExampleMethod are valid: ExampleMethod(True) ExampleMethod(False, 10) 7.18 Optional Parameters

100  2009 Pearson Education, Inc. All rights reserved. 100 Common Programming Error 7.11 Not specifying a default value for an Optional parameter is a syntax error. 7.18 Optional Parameters (Cont.) Common Programming Error 7.10 Declaring a non- Optional parameter to the right of an Optional parameter is a syntax error.

101  2009 Pearson Education, Inc. All rights reserved. 101 Outline Power.vb (1 of 3 ) The example in Fig. 7.21 demonstrates the use of optional parameters. Using values from both TextBox es. Using the value of one TextBox and omitting the optional parameter. Fig. 7.21 | Optional argument demonstration with method Power. (Part 1 of 3.)

102  2009 Pearson Education, Inc. All rights reserved. 102 Outline Power.vb (2 of 3 ) Using values from both TextBox es. a) baseTextBoxpowerTextBox Fig. 7.21 | Optional argument demonstration with method Power. (Part 2 of 3.)

103  2009 Pearson Education, Inc. All rights reserved. 103 Outline Power.vb (3 of 3 ) b) Power not necessary, optional parameter c) calculateButton Fig. 7.21 | Optional argument demonstration with method Power. (Part 3 of 3.)

104  2009 Pearson Education, Inc. All rights reserved. 104 A recursive method calls itself either directly or indirectly. Recursive problem-solving approaches have a number of elements in common: – The method solves only the simplest case—the base case. – When presented with a more complicated problem, the method invokes a fresh copy of itself to work on a smaller problem. A sequence of returns travels back up the line until the original method call returns the final result. 7.19 Recursion

105  2009 Pearson Education, Inc. All rights reserved. 105 Determining a Factorial Value Recursively The factorial of a nonnegative integer n, written n! (and read “n factorial”), is the product n. ( n – 1 ). ( n – 2 ). …. 1 We arrive at a recursive definition of the factorial method by observing the following relationship: n ! = n. ( n – 1 )! 7.19 Recursion (Cont.)

106  2009 Pearson Education, Inc. All rights reserved. 106 Fig. 7.22 | Recursive evaluation of 5!. A recursive evaluation of 5! would proceed as in Fig. 7.22. 7.19 Recursion (Cont.)

107  2009 Pearson Education, Inc. All rights reserved. 107 Outline Factorial Calculator.vb (1 of 2 ) Figure 7.23 recursively calculates and prints factorials. If number is less than or equal to 1, Factorial returns 1 and the method returns. If number is greater than 1, the answer is expressed as the product of number and a recursive call to Factorial. Fig. 7.23 | Recursive factorial program. (Part 1 of 2.)

108  2009 Pearson Education, Inc. All rights reserved. 108 Outline Factorial Calculator.vb (2 of 2 ) Determining if the factorial has been resolved to its simplest form. Factorial makes recursive calls. Fig. 7.23 | Recursive factorial program. (Part 2 of 2.)

109  2009 Pearson Education, Inc. All rights reserved. 109 Set the output TextBox ’s ScrollBars property to Vertical to display more outputs. Type Long is designed to store integer values in a range much larger than that of type Integer (such as factorials greater than 12!). The TextBox ’s Clear method clears the text. Common Programming Error 7.12 Forgetting to return a value from a recursive method can result in logic errors. 7.19 Recursion (Cont.)

110  2009 Pearson Education, Inc. All rights reserved. 110 Common Programming Error 7.13 Omitting the base case or writing the recursion step so that it does not converge on the base case will cause infinite recursion, eventually exhausting memory. This is analogous to the problem of an infinite loop in an iterative (nonrecursive) solution. 7.19 Recursion (Cont.)

111  2009 Pearson Education, Inc. All rights reserved. 111 7.20 (Optional) Software Engineering Case Study: Identifying Class Operations in the ATM System An operation is a service that objects of a class provide to clients of the class. We can derive many of the operations of the classes in our ATM system by examining the verbs and verb phrases in the requirements document (Fig. 7.24).

112  2009 Pearson Education, Inc. All rights reserved. 112 Fig. 7.24 | Verbs and verb phrases for each class in the ATM system. 7.20 (Optional) Software Engineering Case Study: Identifying Class Operations in the ATM System (Cont.)

113  2009 Pearson Education, Inc. All rights reserved. 113 7.20 (Optional) Software Engineering Case Study: Identifying Class Operations in the ATM System (Cont.) The UML represents operations (which are implemented as methods) as follows: operationName ( parameter1, parameter2, …, parameterN ) : returnType Each parameter consists of a parameter name and type: parameterName : parameterType

114  2009 Pearson Education, Inc. All rights reserved. 114 7.20 (Optional) Software Engineering Case Study: Identifying Class Operations in the ATM System (Cont.) Fig. 7.25 | Classes in the ATM system with attributes and operations.

115  2009 Pearson Education, Inc. All rights reserved. 115 7.20 (Optional) Software Engineering Case Study: Identifying Class Operations in the ATM System (Cont.) Fig. 7.26 | Class BankDatabase with operation parameters. Fig. 7.27 | Class Account with operation parameters.

116  2009 Pearson Education, Inc. All rights reserved. 116 7.20 (Optional) Software Engineering Case Study: Identifying Class Operations in the ATM System (Cont.) Fig. 7.28 | Class Screen with an operation parameters. Fig. 7.29 | Class CashDispenser with operation parameters.


Download ppt " 2009 Pearson Education, Inc. All rights reserved. 1 7 7 Methods: A Deeper Look."

Similar presentations


Ads by Google