+ All Categories
Home > Documents > Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes...

Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes...

Date post: 08-Mar-2021
Category:
Upload: others
View: 3 times
Download: 0 times
Share this document with a friend
116
1 7 7 7 7 Methods: A Methods: A Deeper Look 2009 Pearson Education, Inc. All rights reserved.
Transcript
Page 1: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

1

7777Methods: AMethods: ADeeper Look p

2009 Pearson Education, Inc. All rights reserved.

Page 2: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

2

The greatest invention of the nineteenth centuryThe greatest invention of the nineteenth century was the invention of the method of invention.

– Alfred North Whiteheaded No t W te ead

Form ever follows function.f f– Louis Henri Sullivan

Call me Ishmael.– Herman Melville, Moby Dick

When you call me that, smile!– Owen Wister

2009 Pearson Education, Inc. All rights reserved.

– Owen Wister

Page 3: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

3

O! call back yesterday bid time returnO! call back yesterday, bid time return.– William Shakespeare

Answer me in one word.– William Shakespearep

There is a point at whichmethods devour themselves.

– Frantz Fanon

2009 Pearson Education, Inc. All rights reserved.

Page 4: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

4

OBJECTIVESOBJECTIVESIn this chapter you will learn:

T t t d l l f To construct programs modularly from methods.Th t h d th d i t d ith That Shared methods are associated with a class rather than a specific instance of the classclass. To use common Math methods from the

Framework Class LibraryFramework Class Library. To create new methods.

2009 Pearson Education, Inc. All rights reserved.

Page 5: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

5

OBJECTIVESOBJECTIVES The mechanisms used to pass information

between methodsbetween methods. Simulation techniques that employ random

number generationnumber generation. How the visibility of identifiers is limited to

specific regions of programsspecific regions of programs. To write and use recursive methods

(methods that call themselves)(methods that call themselves).

2009 Pearson Education, Inc. All rights reserved.

Page 6: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

6

7.1 Introduction7.2 Modules, Classes and Methods 7.3 Subroutines: Methods That Do Not Return a Value7 4 Functions: Methods That Return a Value7.4 Functions: Methods That Return a Value 7.5 Shared Methods and Class Math7.6 GradeBook Case Study: Declaring Methods with

M l i l PMultiple Parameters 7.7 Notes on Declaring and Using Methods 7.8 Method Call Stack and Activation Records7.8 Method Call Stack and Activation Records7.9 Implicit Argument Conversions 7.10 Option Strict and Data-Type Conversions

2009 Pearson Education, Inc. All rights reserved.

Page 7: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

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 y7.14 Scope of Declarations 7.15 Case Study: Random Number Generation

16 C S d A G f Ch7.16 Case Study: A Game of Chance 7.17 Method Overloading 7.18 Optional Parameters7.18 Optional Parameters 7.19 Recursion 7.20 (Optional) Software Engineering Case Study:

Id tif i Cl O ti i th ATM S tIdentifying Class Operations in the ATM System

2009 Pearson Education, Inc. All rights reserved.

Page 8: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

8

7.2 Modules, Classes and Methods

• Programs consist of many pieces, including modulesPrograms consist of many pieces, including modules and classes.

• Modules and classes are composed of methods, fieldsModules 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.g p p

2009 Pearson Education, Inc. All rights reserved.

Page 9: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

9

7.2 Modules, Classes and Methods (Cont.)

Software Engineering Observation 7 1

(Cont.)

Software Engineering Observation 7.1When possible, use .NET Framework classes and methods instead of writing new classes and methods. gThis 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.

2009 Pearson Education, Inc. All rights reserved.

Page 10: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

10

7.2 Modules, Classes and Methods (Cont.)(Cont.)

• A method is invoked by a method call.h h d ll ifi h h d d id– The method call specifies the method name and provides

information.– When the method completes its task, it returns control to the p ,

caller.

• In some cases, the method also returns a result to the llcaller.

2009 Pearson Education, Inc. All rights reserved.

Page 11: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

11

7.2 Modules, Classes and Methods (Cont.)(Cont.)

• A boss (the caller) asks a worker (the callee) to perform a t k d t th lt h th t k i dtask 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)unaware of this (Fig. 7.1).

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.1 | Hierarchical boss-method/worker-method relationship.

Page 12: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

12

7.2 Modules, Classes and Methods (Cont.)(Cont.)

Software Engineering Observation 7.2To 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 tasktask, and the name of the method should express that task effectively.

Software Engineering Observation 7.3If 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.

2009 Pearson Education, Inc. All rights reserved.

dividing such a method into several smaller methods.

Page 13: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

13Outline

• Subroutines (such as Console.WriteLine) do not

Payment.vb

(1 of 2 )

return a value.

• The console application in Fig. 7.2 uses a subroutineto print a worker’s payment information

1 ' Fig. 7.2: Payment.vb

2 ' Subroutine that prints payment information.

to print a worker s payment information.

2 Subroutine that prints payment information.

3 Module Payment

4 Sub Main()

5 ' call subroutine PrintPay 4 times

6 PrintPay(40, 10.5)

7 P i tP (38 21 75) i 7 PrintPay(38, 21.75)

8 PrintPay(20, 13)

9 PrintPay(30, 14)

10 End Sub ' Main

Main makes four calls to the subroutine PrintPay.

Fig. 7.2 | Subroutine for printing payment information. (Part 1 of 2.)

2009 Pearson Education, Inc. All rights reserved.

Page 14: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

14Outline

Payment.vb

(2 of 2 )

11 12 ' print dollar amount earned in console window 13 Sub PrintPay(ByVal hours As Double, ByVal wage As Decimal) 14 ' pay = hours * wage

l i i (" h i { }" h )

Method PrintPay15 Console.WriteLine("The payment is {0:C}", hours * wage) 16 End Sub ' PrintPay 17 End Module ' Payment

The payment is $420.00

Th t i $826 50

is a subroutine.

The payment is $826.50

The payment is $260.00

The payment is $420.00

Fi 7 2 | S b ti f i ti t i f ti (P t 2 f 2 )Fig. 7.2 | Subroutine for printing payment information. (Part 2 of 2.)

2009 Pearson Education, Inc. All rights reserved.

Page 15: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

15

7.3 Subroutines: Methods That Do Not Return a Value (Cont.)Return a Value (Cont.)

• The format of a subroutine declaration is:The format of a subroutine declaration is:Sub method-name(parameter-list)

declarations and statementsEnd Sub

• The parameter-list is a comma-separated list of each ’ dparameter’s type and name.

– The type of each argument must be consistent with its corresponding parameter’s type.co espo d g pa a ete s type.

– If a method does not receive any values, the method name is followed by an empty set of parentheses.

2009 Pearson Education, Inc. All rights reserved.

Page 16: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

16

7.3 Subroutines: Methods That Do Not Return a Value (Cont.)Common Programming Error 7.1Declaring a variable in the method’s body with the same

Return a Value (Cont.)

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.1pAlthough it is allowable, an argument passed to a method should not have the same name as the corresponding

t i th th d d l ti Thi tparameter name in the method declaration. This prevents ambiguity that could lead to logic errors.

2009 Pearson Education, Inc. All rights reserved.

Page 17: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

17

7.3 Subroutines: Methods That Do Not Return a Value (Cont.)Return a Value (Cont.)

• The method body (also referred to as a block) contains d l ti d t t tdeclarations and statements.

• The body of a method declared with Sub must be terminated with End Sub

Software Engineering Observation 7.4

terminated with End Sub.

Method names tend to be verbs because methods typically perform actions. By convention, method names begin withan uppercase first letter. For example, a method that sends anan uppercase first letter. For example, a method that sends an e-mail message might be named SendMail.

2009 Pearson Education, Inc. All rights reserved.

Page 18: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

18

7.3 Subroutines: Methods That Do Not Return a Value (Cont.)Error-Prevention Tip 7.2Small methods are easier to test debug and understand

Return a Value (Cont.)

Small methods are easier to test, debug and understandthan large methods.

Good Programming Practice 7.1When a parameter is declared without a type, its type is p yp , ypassumed to be Object. Explicitly declaring a parameter’s type improves program clarity.

2009 Pearson Education, Inc. All rights reserved.

Page 19: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

19Outline

• Functions are methods that return a valueSquareInteger.vb

(1 of 2 )

Functions are methods that return a valueto the caller.

• The console application in Fig. 7.3 uses the function

1 ' Fig. 7.3: SquareInteger.vb

Square to calculate the squares of the integersfrom 1–10.

2 ' Function that squares a number.

3 Module SquareInteger

4 Sub Main()

5 Console.WriteLine("Number" & vbTab & "Square")

6 6 7 ' square integers from 1 to 10

8 For counter = 1 To 10

9 Console.WriteLine(counter & vbTab & Square(counter))

10 Next 11 End Sub ' Main

The For…Next statement displays the results of squaring the integers.11 End Sub ' Main

integers.

Fig. 7.3 | Function for squaring an integer. (Part 1 of 2.)

2009 Pearson Education, Inc. All rights reserved.

Page 20: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

20Outline

SquareInteger.vb

(2 of 2 )

12 13 ' function Square is executed when it is explicitly called 14 Function Square(ByVal y As Integer) As Integer 15 Return y ^ 2 ' return square of parameter value 16 End Function ' Square

Square receives a copy of counter’s value.

16 End Function Square

17 End Module ' SquareInteger

Number Square

1 1

2 4

The Returnstatementterminates the method and returns the result.2 4

3 9

4 16

5 25

6 36

7 49

8 64

9 81

10 100

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.3 | Function for squaring an integer. (Part 2 of 2.)

Page 21: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

21

7.4 Functions: Methods That Return a Value (Cont.)Value (Cont.)

• The Return statement terminates the method and returns the resultreturns the result.

• The return statement can occur anywhere in a function bodybody.

Return expression

• The return-type indicates the type of the result returned from the function.

2009 Pearson Education, Inc. All rights reserved.

Page 22: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

22

7.4 Functions: Methods That Return a Value (Cont.)Value (Cont.)Common Programming Error 7.2If the expression in a Return statement cannot be convertedIf 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.3Failure to return a value from a function (e g by forgettingFailure 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 i t t tincorrect output.

2009 Pearson Education, Inc. All rights reserved.

Page 23: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

23

7.5 Shared Methods and Class Math

• A method which performs a task that does not depend bj i k Sh d h don an object is known as a Shared method.

– Place the Shared modifier before the keyword Sub or FunctionFunction.

• To call a Shared method:ClassName.MethodName(arguments)

• Class Math provides a collection of Shared methods:pMath.Sqrt(900.0)

2009 Pearson Education, Inc. All rights reserved.

Page 24: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

24

7.5 Shared Methods and Class Math (Cont.)(Cont.)Software Engineering Observation 7.5It is not necessary to add an assembly reference to use theIt 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.imported in all .NET applications.

2009 Pearson Education, Inc. All rights reserved.

Page 25: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

25

7.5 Shared Methods and Class Math (Cont.)

• Figure 7.4 summarizes several Math class methods.In the figure x and y are of type Double

(Cont.)

Method Description Example

In the figure, x and y are of type Double.

Abs(x) returns the absolute value of x Abs(23.7) is 23.7 Abs(0) is 0 Abs(-23.7) is 23.7

Ceiling(x) rounds x to the smallest integer not Ceiling(9.2) is 10.0 g( ) gless than x

g( )

Ceiling(-9.8) is -9.0

Cos(x) returns the trigonometric cosine of x (x in radians)

Cos(0.0) is 1.0

Exp(x) returns the exponential ex Exp(1.0) is approximately 2.71828182845905 Exp(2.0) is approximately 7.38905609893065

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.4 | Math class methods. (Part 1 of 3.)

Page 26: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

26

7.5 Shared Methods and Class Math (Cont.)(Cont.)

Method Description Example

Floor(x) rounds x to the closets integer less than or equal to x

Floor(9.2) is 9.0 Floor(-9.8) is -10.0 ( )

Log(x) returns the natural logarithm of x (base e)

Log(2.7182818284590451) is approximately 1.0 Log(7.3890560989306504) is approximately 2.0

Max(x, y) returns the larger value of x and y Max(2.3, 12.7) is 12.7 Max(-2.3, -12.7) is -2.3

Min(x, y) returns the smaller value of x and y Min(2.3, 12.7) is 2.3

Fig. 7.4 | Math class methods. (Part 2 of 3.)

y yMin(-2.3, -12.7) is -12.7

2009 Pearson Education, Inc. All rights reserved.

Page 27: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

27

7.5 Shared Methods and Class Math (Cont.)(Cont.)

Method Description Example

Pow(x, y) calculates x raised to the power y (xy) Pow(2.0, 7.0) is 128.0 Pow(9.0, .5) is 3.0

Sin(x) returns the trigonometric sine of x (x in radians)

Sin(0.0) is 0.0

Sqrt(x) returns the square root of x Sqrt(9 0) is 3 0 Sqrt(x) returns the square root of x Sqrt(9.0) is 3.0 Sqrt(2.0) is 1.4142135623731

Tan(x) returns the trigonometric tangent of x (x in radians)

Tan(0.0) is 0.0 g ( )

Fig. 7.4 | Math class methods. (Part 3 of 3.)

2009 Pearson Education, Inc. All rights reserved.

Page 28: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

28

7.5 Shared Methods and Class Math (Cont.)(Cont.)

• Math.PI and Math.E are declared in class Mathi h h difi bli d C twith the modifiers Public and Const.– Const declares a constant—a value that cannot be changed.

Constants are implicitly Shared– Constants are implicitly Shared.

2009 Pearson Education, Inc. All rights reserved.

Page 29: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

29Outline

• The application in Figs. 7.5–7.6 uses a

GradeBook.vb

(1 of 5 )

The application in Figs 7 5 7 6 uses auser-declared method called Maximum todetermine the largest of three Integer values.

1 ' Fig. 7.5: GradeBook.vb

2 ' Definition of class GradeBook that finds the maximum of three grades.

3 Public Class GradeBook

4 Private courseNameValue As String ' name of course

5 Private maximumGrade As Integer ' maximum of three grades 5 Private maximumGrade As Integer maximum of three grades

6 7 ' constructor initializes course name

8 Public Sub New(ByVal name As String)

9 CourseName = name ' initializes CourseName

10 maximumGrade = 0 ' this value will be replaced by maximum grade 11 End Sub ' New 12

Fig 7 5 | User-declared method Maximum that has threeFig. 7.5 | User-declared method Maximum that has threeInteger parameters. (Part 1 of 5.)

2009 Pearson Education, Inc. All rights reserved.

Page 30: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

30Outline

13 ' property that gets and sets the course name; the Set accessor 14 ' ensures that the course name has at most 25 characters 15 Public Property CourseName() As String 16 Get ' retrieve courseNameValue 17 Return courseNameValue

GradeBook.vb

(2 of 5 )17 Return courseNameValue 18 End Get 19 20 Set(ByVal value As String) ' set courseNameValue 21 If value.Length <= 25 Then ' if value has 25 or fewer characters 22 courseNameValue = value ' store the course name in the object 23 Else ' if name has more than 25 characters 24 ' set courseNameValue to first 25 characters of parameter name 25 ' start at 0, length of 25 26 courseNameValue = value.Substring(0, 25) g( , )

27 28 Console.WriteLine( _ 29 "Course name (" & value & ") exceeds maximum length (25).") 30 Console.WriteLine( _ 31 "Limiting course name to first 25 characters " & vbNewLine) 31 Limiting course name to first 25 characters. & vbNewLine)

32 End If 33 End Set 34 End Property ' CourseName

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.5 | User-declared method Maximum that has threeInteger parameters. (Part 2 of 5.)

Page 31: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

31

35

Outline

35 36 ' display a welcome message to the GradeBook user 37 Public Sub DisplayMessage() 38 Console.WriteLine("Welcome to the grade book for " _ 39 & vbNewLine & CourseName & "!" & vbNewLine)

GradeBook.vb

(3 of 5 )

40 End Sub ' DisplayMessage 41 42 ' input three grades from user 43 Public Sub InputGrades() 44 Dim grade1 As Integer ' first grade entered by user 44 Dim grade1 As Integer first grade entered by user

45 Dim grade2 As Integer ' second grade entered by user 46 Dim grade3 As Integer ' third grade entered by user 47 48 Console.Write("Enter the first grade: ") 49 d 1 C l R dLi () 49 grade1 = Console.ReadLine() 50 Console.Write("Enter the second grade: ") 51 grade2 = Console.ReadLine() 52 Console.Write("Enter the third grade: ") 53 grade3 = Console.ReadLine() 54 55 ' store the maximum in maximumGrade 56 maximumGrade = Maximum(grade1, grade2, grade3) 57 End Sub ' InputGrades

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.5 | User-declared method Maximum that has threeInteger parameters. (Part 3 of 5.)

Page 32: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

32Outline

58 59 ' returns the maximum of its three integer parameters 60 Function Maximum(ByVal x As Integer, ByVal y As Integer, _ 61 ByVal z As Integer) As Integer

GradeBook.vb

(4 of 5 )61 ByVal z As Integer) As Integer 62 63 Dim maximumValue As Integer = x ' assume x is the largest to start 64 65 ' determine whether y is greater than maximumValue 66 If (y > maximumValue) Then 67 maximumValue = y ' make y the new maximumValue 68 End If 69

Fig. 7.5 | User-declared method Maximum that has threeInteger parameters. (Part 4 of 5.)

2009 Pearson Education, Inc. All rights reserved.

Page 33: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

33Outline

70 ' determine whether z is greater than maximumValue 71 If (z > maximumValue) Then 72 maximumValue = z ' make z the new maximumValue 73 E d If

GradeBook.vb

(5 of 5 )73 End If 74 75 Return maximumValue 76 End Function ' Maximum 77 78 ' display a report based on the grades entered by user 79 Public Sub DisplayGradeReport() 80 ' output maximum of grades entered 81 Console.WriteLine("Maximum of grades entered: " & maximumGrade) 82 End Sub ' DisplayGradeReport p y p

83 End Class ' GradeBook

Fig. 7.5 | User-declared method Maximum that has threeInteger parameters. (Part 5 of 5.)

2009 Pearson Education, Inc. All rights reserved.

Page 34: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

34Outline

1 ' Fig. 7.6: GradeBookTest.vb

2 ' Create a GradeBook object, input grades and display grade report.

3 Module GradeBookTest

4 Sub Main()

GradeBookTest.vb

(1 of 2 ) 4 Sub Main()

5 ' create GradeBook object

6 Dim gradeBook1 As New GradeBook("CS101 Introduction to VB")

7 8 gradeBook1.DisplayMessage() ' display welcome message

9 gradeBook1.InputGrades() ' read grades from user

10 gradeBook1.DisplayGradeReport() ' display report based on grades 11 End Sub ' Main 12 End Module ' GradeBookTest

Welcome to the grade book for

CS101 Introduction to VB!

Enter the first grade: 65

Enter the second grade: 87

Enter the third grade: 45 Enter the third grade: 45

Maximum of grades entered: 87

(continued on next page...)

Fig. 7.6 | Application to test class GradeBook’s Maximum method. (Part 1 of 2.)

2009 Pearson Education, Inc. All rights reserved.

g ( )

Page 35: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

35Outline

(continued from previous page…) Welcome to the grade book for

GradeBookTest.vb

(2 of 2 )g

CS101 Introduction to VB!

Enter the first grade: 45

Enter the second grade: 65

Enter the third grade: 87

i f d dMaximum of grades entered: 87

Welcome to the grade book for

CS101 Introduction to VB!

Enter the first grade: 87

Enter the second grade: 45

Enter the third grade: 65

Maximum of grades entered: 87

Fig. 7.6 | Application to test class GradeBook’s Maximum method. (Part 2 of 2.)

2009 Pearson Education, Inc. All rights reserved.

Page 36: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

36

7.7 Notes on Declaring and Using Methods

• There are three ways to call a method:

Methods

– 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 objectmethod 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 Sharedmethods.

2009 Pearson Education, Inc. All rights reserved.

Page 37: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

37

7.7 Notes on Declaring and Using Methods (Cont.)Common Programming Error 7.4Declaring a method outside the body of a class or module declaration

Methods (Cont.)

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.5Omitting the return-value-type in a method declaration, if that method is a function, is a syntax error.

Common Programming Error 7 6Common Programming Error 7.6Redeclaring a method parameter as a local variable in the method’s body is a compilation error. y p

Common Programming Error 7.7Returning a value from a method that is a subroutine is a

2009 Pearson Education, Inc. All rights reserved.

compilation error.

Page 38: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

38

7.8 Method Call Stack and Activation RecordsRecords

• A data structure known as a stack is analogous to a pile f di hof dishes.– When a dish is placed on the pile, it is placed at the top

(pushing onto the stack)(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.

2009 Pearson Education, Inc. All rights reserved.

Page 39: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

39

7.8 Method Call Stack and Activation Records (Cont.)Records (Cont.)

• When a program calls a method, the return address of h ll i h d h h d ll kthe 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.

2009 Pearson Education, Inc. All rights reserved.

Page 40: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

40

7.9 Implicit Argument Conversions

• An important feature of argument passing is implicit iargument conversion.

– A widening conversion occurs when an argument is converted to another type that can hold more dataanother type that can hold more data.

– A narrowing conversion occurs when there is potential for data loss during the conversion.

2009 Pearson Education, Inc. All rights reserved.

Page 41: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

41

7.9 Implicit Argument Conversions (Cont.)(Cont.)

• Figure 7.7 lists the widening conversions supported by Visual BasicVisual Basic.

Type Conversion types

Boolean no possible widening conversions to other primitive types

Byte UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single or Double

Char String Char String

Date no possible widening conversions to other primitive types

Decimal Single or Double

Double no possible widening conversions to other primitive types Double no possible widening conversions to other primitive types

Integer Long, Decimal, Single or Double

Long Decimal, Single or Double

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.7 | Widening conversions between primitive types. (Part 1 of 2.)

Page 42: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

42

7.9 Implicit Argument Conversions (Cont.)(Cont.)

Type Conversion types

SByte Short, Integer, Long, Decimal, Single or Double

Short Integer, Long, Decimal, Single or Double

Single Double

String no possible widening conversions to other primitive types

UInteger ULong, Long, Decimal, Single or Double

ULong Decimal, Single or Double

UShort UInteger, Integer, ULong, Long, Decimal, Single or Double

Fig. 7.7 | Widening conversions between primitive types. (Part 2 of 2.)

2009 Pearson Education, Inc. All rights reserved.

Page 43: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

43

7.9 Implicit Argument Conversions (Cont.)(Cont.)

Common Programming Error 7.8Converting a primitive type value to a value of anotherConverting 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 g p , gfloating-point value to an integral value truncates any fractional part of the floating-point value (e.g., 4.7 b 4)becomes 4).

2009 Pearson Education, Inc. All rights reserved.

Page 44: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

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 “ id t” t i th i“widest” type in the expression.

• The value of integerNumber is converted to type Single for this operation:

i l b i bsingleNumber + integerNumber

2009 Pearson Education, Inc. All rights reserved.

Page 45: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

45

7.10 Option Strict and Data-Type ConversionsConversions• 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.p p p

Compile tab

Drop-down list to modifyOption Explicit

Drop-down list to modify Option Strict

Drop-down list to modify Option Infer

2009 Pearson Education, Inc. All rights reserved.Fig. 7.8 | Modifying Option Strict and Option Explicit.

Page 46: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

46

7.10 Option Strict and Data-Type Conversions (Cont.)Conversions (Cont.)

• Option Strict requires explicit conversion for all i inarrowing 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())

2009 Pearson Education, Inc. All rights reserved.

Page 47: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

47

7.10 Option Strict and Data-Type Conversions (Cont.)Conversions (Cont.)

• Option Infer enables the compiler to infer a i bl ’ b d i i i i li lvariable’s type based on its initializer value.

• You can set the default values of Option Explicit, O ti St i t d O ti I fOption Strict and Option Infer.

– Select Tools > Options...Under Projects and Solutions select VB Defaults– Under Projects and Solutions, select VB Defaults

– Choose the appropriate value in each option’s ComboBox.

Error-Prevention Tip 7.3From this point forward, all code examples have OptionSt ict t t On

2009 Pearson Education, Inc. All rights reserved.

Strict set to On.

Page 48: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

48

7.11 Value Types and Reference Types

• All Visual Basic types can be categorized as either l fvalue types or reference types.

– A variable of a value type contains data of that type.A i ble f efe e e t e t i the dd e f the l ti– A variable of a reference type contains the address of the location in memory where the data is stored.

2009 Pearson Education, Inc. All rights reserved.

Page 49: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

49

7.11 Value Types and Reference Types (Cont.)(Cont.)

Type

Size in bits Values Standard

Name of .NET class or structure

Boolean True or False Boolean

Byte 8 0 to 255 Byte

SByte 8 -128 to 127 SByte

Char 16 One Unicode character (Unicode character set)

Char

Date 64 1 January 0001 to 31 December 9999

DateTime

Fig 7 9 | Primitive types (Part 1 of 3 )

12:00:00 AM to 11:59:59 PM

Decimal 128 1.0E-28 to 7.9E+28 Decimal

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.9 | Primitive types. (Part 1 of 3.)

Page 50: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

50

7.11 Value Types and Reference Types (Cont.)(Cont.)

Type

Size in bits Values Standard

Name of .NET class or structure

Double 64 ±5 0E 324 to ±1 7E+308 (IEEE 754 Double Double 64 ±5.0E–324 to ±1.7E+308 (IEEE 754floating point)

Double

Integer 32 –2,147,483,648 to 2,147,483,647

Int32

Long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Int64

Short 16 –32,768 to 32,767 Int16

Single 32 ±1 5E-45 to ±3 4E+38 (IEEE 754 Single Single 32 ±1.5E-45 to ±3.4E+38 (IEEE 754 floating point)

Single

Fig. 7.9 | Primitive types. (Part 2 of 3.)

2009 Pearson Education, Inc. All rights reserved.

Page 51: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

51

7.11 Value Types and Reference Types (Cont.)(Cont.)

T pe

Size in bits Val es Standard

Name of .NET class or str ct re Type bits Values Standard or structure

String 0 to ~2000000000 Unicode characters

(Unicode character set)

String

UInteger 32 0 to 4,294,967,295 UInt32

ULong 64 0 to 18,446,744,073,709,551,615 UInt64

UShort 16 0 to 65,535 UInt16

Fig. 7.9 | Primitive types. (Part 3 of 3.)

2009 Pearson Education, Inc. All rights reserved.

Page 52: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

52

7.12 Framework Class Library NamespacesNamespaces

• The .NET framework contains many classes grouped into over 100 namespacesinto over 100 namespaces.

A i l d h d l i• A program includes the an Imports declaration to use classes from that namespace:

Imports System Windows FormsImports System.Windows.Forms

2009 Pearson Education, Inc. All rights reserved.

Page 53: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

53

7.12 Framework Class Library Namespaces (Cont.)Namespaces (Cont.)

• Some key namespaces are described in Fig. 7.10.

Namespace Description

System.Windows.Forms Contains the classes required to create and manipulate GUIs.

System.IO Contains classes that enable programs to input and output data.

System.Data Contains classes that enable programs to access and manipulate databasesy Contains classes that enable programs to access and manipulate databases (i.e., an organized collection of data).

System.Web Contains classes used for creating and maintaining Web applications, which are accessible over the Internet.

System.Xml Contains classes for creating and manipulating XML data. Data can be read from or written to XML files.

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.10 | .NET Framework Class Library namespaces (a subset). (Part 1 of 2.)

Page 54: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

54

7.12 Framework Class Library Namespaces (Cont.)Namespaces (Cont.)

Namespace Description

System.Collections Contains classes that define data structures for maintaining collections of data.

System.Net Contains classes that enable programs to communicate via computer networks like the Internet.

System.Text Contains classes and interfaces that enable programs to manipulate characters and stringscharacters and strings.

System.Threading Contains classes that enable programs to perform several tasks concurrently, or at the same time.

System.Drawing Contains classes that enable programs to display basic graphics such as System.Drawing Contains classes that enable programs to display basic graphics, such as displaying shapes and arcs.

Fig. 7.10 | .NET Framework Class Library namespaces (a subset). (Part 2 of 2.)

2009 Pearson Education, Inc. All rights reserved.

Page 55: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

55

7.12 Framework Class Library Namespaces (Cont.)Namespaces (Cont.)

Good Programming Practice 7.2The 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 ina class in this book, you should read about the class in the online documentation.

2009 Pearson Education, Inc. All rights reserved.

Page 56: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

56

7.13 Passing Arguments: Pass-by-Value vs. Pass-by-Referencevs. Pass by Reference

• Arguments are passed pass-by-value orpass by referencepass-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 py g p py gthe copy do not affect the original variable.

– When an argument is passed by reference, the original data can be accessed and modified directlybe accessed and modified directly.

2009 Pearson Education, Inc. All rights reserved.

Page 57: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

57Outline

• Figure 7.11 demonstrates passing arguments

1 ' Fig. 7.11: ByRefTest.vb

2 ' Demonstrates passing by value and by reference.

ByRefTest.vb

(1 of 4 )

Figure 7 11 demonstrates passing argumentsby value and by reference.

2 Demonstrates passing by value and by reference.

3 Module ByRefTest

4 Sub Main()

5 Dim number1 As Integer = 2

6 7 Console WriteLine("Passing a al e t pe arg ment b al e ") 7 Console.WriteLine("Passing a value-type argument by value:")

8 Console.WriteLine("Before calling SquareByValue, " & _

9 "number1 is {0}", number1)

10 SquareByValue(number1) ' passes number1 by value 11 Console.WriteLine("After returning from SquareByValue, " & _ 12 "number1 is {0}" & vbNewLine, number1) 13

Fig. 7.11 | ByVal and ByRef used to pass value-type arguments. (Part 1 of 4.)

2009 Pearson Education, Inc. All rights reserved.

Page 58: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

58Outline

14 Dim number2 As Integer = 2 15 16 Console.WriteLine("Passing a value-type argument" & _ 17 " b f ")

ByRefTest.vb

(2 of 4 )17 " by reference:") 18 Console.WriteLine("Before calling SquareByReference, " & _ 19 "number2 is {0}", number2) 20 SquareByReference(number2) ' passes number2 by reference 21 Console.WriteLine("After returning from " & _

Squaring number2 by reference.

22 "SquareByReference, number2 is {0}" & vbNewLine, number2) 23 24 Dim number3 As Integer = 2 25 26 Console.WriteLine("Passing a value-type argument" & _

reference.

( g yp g _

27 " by reference, but in parentheses:") 28 Console.WriteLine("Before calling SquareByReference " & _ 29 "using parentheses, number3 is {0}", number3) 30 SquareByReference((number3)) ' passes number3 by value 31 Console WriteLine("After returning from " &

The inner set of

Squaring number1by value.

31 Console.WriteLine( After returning from & _

32 "SquareByReference, number3 is {0}", number3) 33 End Sub ' Main

parentheses evaluates number3to its value and passes this value.

Fi 7 11 | B V l d B R f d t l t t (P t 2 f 4 )

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.11 | ByVal and ByRef used to pass value-type arguments. (Part 2 of 4.)

Page 59: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

59Outline

34 35 ' squares number by value (note ByVal keyword)

ByRefTest.vb

(3 of 4 )q y ( y y )

36 Sub SquareByValue(ByVal number As Integer) 37 Console.WriteLine("After entering SquareByValue, " & _ 38 "number is {0}", number) 39 number *= number 40 Console WriteLine("Before exiting SquareByValue " &

ByVal indicates that its argument is passed by value.

Squaring the numbert l40 Console.WriteLine( Before exiting SquareByValue, & _

41 "number is {0}", number) 42 End Sub ' SquareByValue 43 44 ' squares number by reference (note ByRef keyword)

parameter value.

ByRef receives its 45 Sub SquareByReference(ByRef number As Integer) 46 Console.WriteLine("After entering SquareByReference" & _ 47 ", number is {0}", number) 48 number *= number 49 Console.WriteLine("Before exiting SquareByReference" & _

ByRef receives its parameter by reference.

Squaring the numberparameter’s reference.

g q y

50 ", number is {0}", number) 51 End Sub ' SquareByReference 52 End Module ' ByRefTest

Fi 7 11 | B V l d B R f d t l t t (P t 3 f 4 )

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.11 | ByVal and ByRef used to pass value-type arguments. (Part 3 of 4.)

Page 60: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

60Outline

Passing a value-type argument by value:

ByRefTest.vb

(4 of 4)Before calling SquareByValue, number1 is 2

After entering SquareByValue, number is 2

Before exiting SquareByValue, number is 4

After returning from SquareByValue, number1 is 2

Passing a value type argument by reference: Passing a value-type argument by reference:

Before calling SquareByReference, number2 is 2

After entering SquareByReference, number is 2

Before exiting SquareByReference, number is 4

After returning from SquareByReference, number2 is 4

Passing a value-type argument by reference, but in parentheses:

Before calling SquareByReference using parentheses, number3 is 2

After entering SquareByReference, number is 2

Before exiting SquareByReference, number is 4

After returning from SquareByReference, number3 is 2

Fig. 7.11 | ByVal and ByRef used to pass value-type arguments. (Part 4 of 4.)

2009 Pearson Education, Inc. All rights reserved.

Page 61: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

61Outline

ByRefTest.vb

(5 of 5 )

Error-Prevention Tip 7.4When 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 systemsdevelopment 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.

2009 Pearson Education, Inc. All rights reserved.

Page 62: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

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 namethat can refer to the declared entity by its name without qualification.

• The basic scopes are:• 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 methodM d l th ti b d f th l d l– Module scope—the entire body of the class or module.

– Namespace scope—accessible to all other elements in the same namespace

2009 Pearson Education, Inc. All rights reserved.

Page 63: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

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 shadowingclass, the field is hidden—this is called shadowing.

• A variable’s lifetime is the period during which the variable exists in memoryvariable exists in memory.

– Variables normally exist as long as their container exists.

Error-Prevention Tip 7.5Use 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.

2009 Pearson Education, Inc. All rights reserved.

name in the class.

Page 64: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

64Outline

1 ' Fig. 7.12: Scope.vb

2 ' Scope class demonstrates instance and local variable scopes.

3 Public Class Scope

Scope.vb

(1 of 2 )

4 ' instance variable that is accessible to all methods of this class

5 Private x As Integer = 1

6 7 ' method Begin creates and initializes local variable x and

8 ' calls methods UseLocalVariable and UseInstanceVariable

This instance variable is shadowed by any local variable named x.

9 Public Sub Begin()

10 ' method's local variable x shadows instance variable x 11 Dim x As Integer = 5 12 13 Console WriteLine("local x in method Begin is " & x)

Method Begin declares a local variable x

13 Console.WriteLine( local x in method Begin is & x)

14 15 UseLocalVariable() ' UseLocalVariable has local x 16 UseInstanceVariable() ' uses class Scope's instance variable x 17 UseLocalVariable() ' UseLocalVariable reinitializes local x 18 UseInstanceVariable() ' Scope's instance variable x retains value 19 20 Console.WriteLine(vbNewLine & "local x in method Begin is " & x) 21 End Sub ' Begin

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.12 | Scoping rules in a class. (Part 1 of 2.)

Page 65: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

65Outline

22 23 ' create and initialize local variable x during each call 24 Sub UseLocalVariable()

Scope.vb

(2 of 2 )24 Sub UseLocalVariable() 25 Dim x As Integer = 25 ' initialized in each call 26 27 Console.WriteLine(vbNewLine & _ 28 "local x on entering method UseLocalVariable is " & x) 29 1 ' difi hi h d' l l i bl

Subroutine UseLocalVariable declares a local variable x

29 x += 1 ' modifies this method's local variable x 30 Console.WriteLine("local variable x before exiting method " & _ 31 "UseLocalVariable is " & x) 32 End Sub ' UseLocalVariable 33

Modifying the local variable x

34 ' modify class Scope's instance variable x during each call 35 Sub UseInstanceVariable() 36 Console.WriteLine(vbNewLine & "instance variable" & _ 37 " x on entering method UseInstanceVariable is " & x) 38 x *= 10 ' modifies class Scope's instance variable x

UseInstanceVariabledoes not declare 38 x 10 modifies class Scope s instance variable x

39 Console.WriteLine("instance variable " & _ 40 "x before exiting method UseInstanceVariable is " & x) 41 End Sub ' UseInstanceVariable 42 End Class ' Scope

local variables, so xrefers to the instance variable.

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.12 | Scoping rules in a class. (Part 2 of 2.)

Page 66: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

66Outline

1 ' Fig. 7.13: ScopeTest.vb

2 ' Testing class Scope.

3 Module ScopeTest

4 Sub Main()

5 Dim testScope As New Scope()

ScopeTest.vb

p p ()

6 testScope.Begin()

7 End Sub ' Main

8 End Module ' ScopeTest

local x in method Begin is 5 g

local x on entering method UseLocalVariable is 25

local variable x before exiting method UseLocalVariable is 26

instance variable x on entering method UseInstanceVariable is 1

finstance variable x before exiting method UseInstanceVariable is 10

local x on entering method UseLocalVariable is 25

local variable x before exiting method UseLocalVariable is 26

instance variable x on entering method UseInstanceVariable is 10 instance variable x on entering method UseInstanceVariable is 10

instance variable x before exiting method UseInstanceVariable is 100

local x in method Begin is 5

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.13 | Module to test class Scope.

Page 67: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

67

7.15 Case Study: Random NumberGenerationGeneration

• The element of chance can be introduced through class Randomclass Random.

Dim randomObject As New Random()

Dim randomNumber As Integer = randomObject.Next()g j ()

• Next generates a positive Integer between zero and Int32.MaxValue.

• The values returned by Next are actuallypseudo-random numbers.

• The default seed value is based on the current time.

2009 Pearson Education, Inc. All rights reserved.

Page 68: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

68

7.15 Case Study: Random NumberGeneration (Cont.)Generation (Cont.)

• We can produce integers in the range 1–6 by passing an argument to method Next:an argument to method Next:

value = 1 + randomObject.Next(6)

• The number 6 is the scaling factor• 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 Ne tNext:

value = randomObject.Next(1, 7)

2009 Pearson Education, Inc. All rights reserved.

Page 69: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

69Outline

• Figure 7.14 demonstrates the use of class Randomand

1 ' Fig. 7.14: RandomInteger.vb

2 ' Random integers from 1 to 6 created by calling Random method Next

3 Module RandomInteger

4 S b M i ()

RandomInteger.vb

andmethod Next by simulating 20 rolls of a six-sided die.

4 Sub Main()

5 Dim randomObject As New Random() ' create Random object

6 Dim randomNumber As Integer

7 8 ' generate 20 random numbers between 1 and 6

Random numbers are generated by an object of class Random.

Th l th t 9 For i = 1 To 20

10 randomNumber = randomObject.Next(1, 7) 11 Console.Write(randomNumber & " ") 12 13 If i Mod 5 = 0 Then ' is i a multiple of 5?

The values that are produced are in the range from 1 to 6, inclusive.

14 Console.WriteLine() 15 End If 16 Next 17 End Sub ' Main 18 End Module ' RandomInteger 18 End Module RandomInteger

1 1 3 1 1

2 1 1 3 6

6 3 4 6 6

2 2 3 6 5

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.14 | Random integers from 1 to 6 created bycalling Random method Next.

Page 70: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

70Outline

1 ' Fig. 7.15: RollDice.vb

2 ' Rolling four dice.

RollDice.vb

(1 of 2 ) 2 Rolling four dice.

3 Public Class RollDice

4 Dim randomObject As New Random() ' create Random object

5 6 ' display results of four rolls

7 Private Sub rollButton Click(ByVal sender As System Object

Initializing a Random object.

7 Private Sub rollButton_Click(ByVal sender As System.Object, _

8 ByVal e As System.EventArgs) Handles rollButton.Click

9 ' method randomly assigns a face to each die

10 DisplayDie(die1PictureBox) 11 DisplayDie(die2PictureBox) 12 DisplayDie(die3PictureBox) 13 DisplayDie(die4PictureBox) 14 End Sub ' rollButton_Click 15

Fig. 7.15 | Demonstrating four die rolls with graphical output. (Part 1 of 2.)

2009 Pearson Education, Inc. All rights reserved.

Page 71: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

71Outline

16 ' get a random die image 17 Sub DisplayDie(ByVal diePictureBox As PictureBox)

RollDice.vb

(2 of 2 )p y ( y )

18 ' generate random integer in range 1 to 6 19 Dim face As Integer = randomObject.Next(1, 7) 20 21 ' retrieve specific die image from resources 22 Dim pictureResource My Resources ResourceManager GetObject(

The values that are produced are in the range from 1 to 6, inclusive.

Retrieving the 22 Dim pictureResource = My.Resources.ResourceManager.GetObject( _ 23 String.Format("die{0}", face)) 24 25 ' convert pictureResource to type Image and display in PictureBox 26 diePictureBox.Image = CType(pictureResource, Image)

CType performs conversion from

Retrieving the picture from My.Resources.

27 End Sub ' DisplayDie 28 End Class ' RollDice

Object to Image.

a) b)

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.15 | Demonstrating four die rolls with graphical output. (Part 2 of 2.)

Page 72: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

72

7.15 Case Study: Random Number Generation (cont.)Generation (cont.)

• The Button control can be simply dragged and dropped onto the Form from the Toolboxdropped 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• Double click the Button to create the Click event handler.

– Note that the event handler is a Sub procedureNote that the event handler is a Sub procedure.

2009 Pearson Education, Inc. All rights reserved.

Page 73: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

73

7.15 Case Study: Random Number Generation (cont.)Generation (cont.)

• The event handler calls method DisplayDie once for each PictureBoxfor each PictureBox.

• Calling DisplayDie causes dice to appear as if they are being rolledare being rolled.

• The images are embedded with the project as resourcesresources.

2009 Pearson Education, Inc. All rights reserved.

Page 74: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

74

7.15 Case Study: Random Number Generation (cont.)Generation (cont.)

– Double click My Project in the Solution Explorer. – Click the Resources tab then click the down arrow next to– Click the Resources tab, then click the down arrow next to

the Add Resource button (Fig. 7.16) to select AddExisting File...L h i h dd d li k h O– Locate the resources you wish to add and click the Openbutton.

– Save your project. y p j

2009 Pearson Education, Inc. All rights reserved.

Page 75: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

75

7.15 Case Study: Random Number Generation (cont.)Generation (cont.)

Fig. 7.16 | Images added as resources.

2009 Pearson Education, Inc. All rights reserved.

Page 76: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

76

7.15 Case Study: Random Number Generation (cont.)Generation (cont.)

• To access the project’s resources, use the method My Resources ResourceManagerMy.Resources.ResourceManager.GetObject.

• You must convert this Object to type Image to• 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• Visual Basic s CType function converts its first argument to the type specified in its second argument.

2009 Pearson Education, Inc. All rights reserved.

Page 77: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

77Outline

1 ' Fig. 7.17: RollTwelveDice.vb

2 ' Rolling 12 dice with frequency chart.

RollTwelveDice.vb

(1 of 5 )g q y

3 Public Class RollTwelveDice

4 Dim randomObject As New Random() ' generate random number

5 Dim ones As Integer ' count of die face 1

6 Dim twos As Integer ' count of die face 2

7 Dim threes As Integer ' count of die face 3

Initializing a Random object.

7 Dim threes As Integer count of die face 3

8 Dim fours As Integer ' count of die face 4

9 Dim fives As Integer ' count of die face 5

10 Dim sixes As Integer ' count of die face 6 11 12 ' display result of twelve rolls 13 Private Sub rollButton_Click(ByVal sender As System.Object, _ 14 ByVal e As System.EventArgs) Handles rollButton.Click 15 16 ' assign random faces to 12 dice using DisplayDie g g p y

17 DisplayDie(die1PictureBox) 18 DisplayDie(die2PictureBox) 19 DisplayDie(die3PictureBox) 20 DisplayDie(die4PictureBox)

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.17 | Random class used to simulate rolling12 six-sided dice. (Part 1 of 5.)

Page 78: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

78Outline

21 DisplayDie(die5PictureBox) 22 DisplayDie(die6PictureBox) 23 DisplayDie(die7PictureBox) 24 Di l Di (di 8Pi t B )

RollTwelveDice.vb

(2 of 5 )24 DisplayDie(die8PictureBox) 25 DisplayDie(die9PictureBox) 26 DisplayDie(die10PictureBox) 27 DisplayDie(die11PictureBox) 28 DisplayDie(die12PictureBox) 29 30 Dim total As Integer = ones + twos + threes + fours + fives + sixes 31 Dim output As String 32 33 ' display frequencies of faces p y q

34 output = ("Face" & vbTab & "Frequency" & vbTab & "Percent") 35 output &= (vbNewLine & "1" & vbTab & ones & _ 36 vbTab & vbTab & String.Format("{0:P2}", ones / total)) 37 output &= (vbNewLine & "2" & vbTab & twos & vbTab & _ 38 vbTab & String Format("{0:P2}" twos / total))

Using String Format to 38 vbTab & String.Format( {0:P2} , twos / total))

39 output &= (vbNewLine & "3" & vbTab & threes & vbTab & _ 40 vbTab & String.Format("{0:P2}", threes / total))

String.Format to print percentages to two decimal places.

Fig. 7.17 | Random class used to simulate rolling

2009 Pearson Education, Inc. All rights reserved.

g | g12 six-sided dice. (Part 2 of 5.)

Page 79: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

79Outline

41 output &= (vbNewLine & "4" & vbTab & fours & vbTab & _ 42 vbTab & String.Format("{0:P2}", fours / total)) 43 output &= (vbNewLine & "5" & vbTab & fives & vbTab & _ 44 vbTab & String Format("{0:P2}" fives / total))

RollTwelveDice.vb

(3 of 5 )44 vbTab & String.Format( {0:P2} , fives / total))

45 output &= (vbNewLine & "6" & vbTab & sixes & vbTab & _ 46 vbTab & String.Format("{0:P2}", sixes / total) & vbNewLine) 47 displayTextBox.Text = output 48 End Sub ' rollButton_Click

Using String.Format to

49 50 ' display a single die image 51 Sub DisplayDie(ByVal diePictureBox As PictureBox) 52 Dim face As Integer = randomObject.Next(1, 7) 53

gprint percentages to two decimal places.

54 ' retrieve specific die image from resources 55 Dim pictureResource = My.Resources.ResourceManager.GetObject( _ 56 String.Format("die{0}", face)) 57 58 ' convert pictureResource to image type and load into PictureBox

Retrieving the picture from My.Resources.

58 convert pictureResource to image type and load into PictureBox

59 diePictureBox.Image = CType(pictureResource, Image) 60

CType performs conversion from Object to Image.

Fig 7 17 | Random class used to simulate rolling

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.17 | Random class used to simulate rolling12 six-sided dice. (Part 3 of 5.)

Page 80: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

80Outline

61 ' maintain count of die faces 62 Select Case face 63 Case 1 ' die face 1 64 1

RollTwelveDice.vb

(4 of 5 )64 ones += 1 65 Case 2 ' die face 2 66 twos += 1 67 Case 3 ' die face 3 68 threes += 1 69 Case 4 ' die face 4 70 fours += 1 71 Case 5 ' die face 5 72 fives += 1 73 Case 6 ' die face 6 73 Case 6 die face 6

74 sixes += 1 75 End Select 76 End Sub ' DisplayDie 77 End Class ' RollTwelveDice

Fig. 7.17 | Random class used to simulate rolling12 six-sided dice. (Part 4 of 5.)

2009 Pearson Education, Inc. All rights reserved.

Page 81: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

81Outline

RollTwelveDice.vb

(5 of 5 )

a) b)

displayTextBox

Fig. 7.17 | Random class used to simulate rolling12 six-sided dice (Part 5 of 5 )

2009 Pearson Education, Inc. All rights reserved.

12 six sided dice. (Part 5 of 5.)

Page 82: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

82

7.15 Case Study: Random Number Generation (cont.)Generation (cont.)

• The TextBox control can be used both for displaying and inputting dataand inputting data.

– The data in the TextBox can be accessed via the Text property.p p y

– This TextBox’s name is displayTextBox and the font size has been set to 9.Th M ltili t h b t t T– The Multiline property has been set to True.

2009 Pearson Education, Inc. All rights reserved.

Page 83: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

83

7.16 Case Study: A Game of Chance

• One of the most popular games of chance is a dice game known as “craps":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 Ifsum 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 theirplayers 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.

2009 Pearson Education, Inc. All rights reserved.

Page 84: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

84Outline

• The application in Fig. 7.18 simulates the

1 ' Fig 7.18: CrapsGame.vb

2 ' Craps game using class Random.

3 Public Class CrapsGame

4 ' di ll t t

CrapsGame.vb

(1 of 7 )

The application in Fig 7 18 simulates the game of craps.

4 ' die-roll constants

5 Enum DiceNames

6 SNAKE_EYES = 2

7 TREY = 3

8 LUCKY_SEVEN = 7 Declaring constants h h 9 CRAPS = 7

10 YO_LEVEN = 11 11 BOX_CARS = 12 12 End Enum 13

through an enumeration.

13 14 Dim myPoint As Integer ' total point 15 Dim myDie1 As Integer ' die1 face 16 Dim myDie2 As Integer ' die2 face 17 Dim randomObject As New Random() ' generate random number 1818

Fig. 7.18 | Craps game using class Random. (Part 1 of 7.)

2009 Pearson Education, Inc. All rights reserved.

Page 85: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

85Outline

19 ' begins new game and determines point 20 Private Sub playButton_Click(ByVal sender As System.Object, _ 21 ByVal e As System.EventArgs) Handles playButton.Click 22

CrapsGame.vb

(2 of 7 )22 23 ' initialize variables for new game 24 myPoint = 0 25 pointGroupBox.Text = "Point" 26 statusLabel.Text = String.Empty String.Empty represents a

string with no characters 27 28 ' remove point-die images 29 pointDie1PictureBox.Image = Nothing 30 pointDie2PictureBox.Image = Nothing 31

Setting the Image to Nothing causes a PictureBox to appear blank

string with no characters ("").

332 Dim sum As Integer = RollDice() ' roll dice and calculate sum 33 34 ' check die roll 35 Select Case sum 36 Case DiceNames LUCKY SEVEN DiceNames YO LEVEN

blank

The Select Casestatement analyzes the

36 Case DiceNames.LUCKY_SEVEN, DiceNames.YO_LEVEN 37 rollButton.Enabled = False ' disable Roll button 38 statusLabel.Text = "You Win!!!"

roll.

Fig 7 18 | Craps game using class Random (Part 2 of 7 )

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.18 | Craps game using class Random. (Part 2 of 7.)

Page 86: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

86Outline

39 Case DiceNames.SNAKE_EYES, DiceNames.TREY, DiceNames.BOX_CARS 40 rollButton.Enabled = False ' disable Roll button 41 statusLabel.Text = "Sorry. You Lose." 42 C El

CrapsGame.vb

(3 of 7 )42 Case Else 43 myPoint = sum 44 pointGroupBox.Text = "Point is " & sum 45 statusLabel.Text = "Roll Again!" 46 DisplayDie(pointDie1PictureBox, myDie1) 47 DisplayDie(pointDie2PictureBox, myDie2) 48 playButton.Enabled = False ' disable Play button 49 rollButton.Enabled = True ' enable Roll button 50 End Select 51 End Sub ' playButton Click 51 End Sub playButton_Click

52

Fig. 7.18 | Craps game using class Random. (Part 3 of 7.)

2009 Pearson Education, Inc. All rights reserved.

Page 87: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

87Outline

53 ' determines outcome of next roll 54 Private Sub rollButton_Click(ByVal sender As System.Object, _ 55 ByVal e As System.EventArgs) Handles rollButton.Click 56

CrapsGame.vb

(4 of 7 )56 57 Dim sum As Integer = RollDice() ' roll dice and calculate sum 58 59 ' check outcome of roll 60 If sum = myPoint Then ' win 61 statusLabel.Text = "You Win!!!" 62 rollButton.Enabled = False ' disable Roll button 63 playButton.Enabled = True ' enable Play button 64 ElseIf sum = DiceNames.CRAPS Then ' lose 65 statusLabel.Text = "Sorry. You Lose."

Determining if a losing roll is made.

65 statusLabel.Text Sorry. You Lose.

66 rollButton.Enabled = False ' disable Roll button 67 playButton.Enabled = True ' enable Play button 68 End If 69 End Sub ' rollButton_Click 7070

Fig. 7.18 | Craps game using class Random. (Part 4 of 7.)

2009 Pearson Education, Inc. All rights reserved.

Page 88: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

88Outline

71 ' display die image 72 Sub DisplayDie(ByVal diePictureBox As PictureBox, _ 73 ByVal face As Integer) 74

CrapsGame.vb

(5 of 7 )74 75 ' retrieve specific die image from resources 76 Dim pictureResource = My.Resources.ResourceManager.GetObject( _ 77 String.Format("die{0}", face)) 78 79 ' convert pictureResource to image type and load into PictureBox 80 diePictureBox.Image = CType(pictureResource, Image) 81 End Sub ' DisplayDie 82

Fig. 7.18 | Craps game using class Random. (Part 5 of 7.)

2009 Pearson Education, Inc. All rights reserved.

Page 89: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

89

83 ' generate random die rolls 84 Function RollDice() As Integer

Outline

84 Function RollDice() As Integer 85 ' determine random integer 86 myDie1 = randomObject.Next(1, 7) 87 myDie2 = randomObject.Next(1, 7) 88

CrapsGame.vb

(6 of 7 )

89 ' display rolls 90 DisplayDie(die1PictureBox, myDie1) 91 DisplayDie(die2PictureBox, myDie2) 92 93 Return myDie1 + myDie2 ' return sum y y

94 End Function ' RollDice 95 End Class ' CrapsGame

a) b)

rollButtonplayButtonpointGroupBox

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.18 | Craps game using class Random. (Part 6 of 7.)

Page 90: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

90Outline

CrapsGame.vb

(7 of 7 )c) d)

Fig. 7.18 | Craps game using class Random. (Part 7 of 7.)

2009 Pearson Education, Inc. All rights reserved.

Page 91: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

91

7.16 Case Study: A Game of Chance (Cont.)• String.Empty represents a string with no

characters ("")

(Cont.)

characters ("").• Setting the Image to Nothing causes a PictureBox to appear blankPictureBox to appear blank.

2009 Pearson Education, Inc. All rights reserved.

Page 92: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

92

7.16 Case Study: A Game of Chance (Cont.)• The GroupBox control is a container used to group

related controls

(Cont.)

related controls.– Within the GroupBox pointDiceGroup, we add two PictureBoxes.

– To add controls to a GroupBox, drag and drop the controls onto it.W t th G B ’ T t t t P i t– We set the GroupBox’s Text property to Point.

2009 Pearson Education, Inc. All rights reserved.

Page 93: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

93

7.16 Case Study: A Game of Chance (Cont.)• Enumerations enhance program readability by

providing descriptive identifiers for constant numbers

(Cont.)

providing descriptive identifiers for constant numbers or Strings.

• In this application we created an Enumeration for the• In this application, we created an Enumeration for the various dice combinations.

• Buttons are enabled and disabled with the• Buttons are enabled and disabled with the Enabled property.

2009 Pearson Education, Inc. All rights reserved.

Page 94: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

94Outline

• Method overloading allows you tot th d ith th b t diff t

Overload.vb

(1 of 2 )

create methods with the same name but differentparameters.

• Figure 7.19 uses overloaded method Square to

1 ' Fig. 7.19: Overload.vb

2 ' Using overloaded methods.

g qcalculate the square of both an Integer and a Double.

3 Module Overload

4 Sub Main() ' call Square methods with Integer then with Double

5 Console.WriteLine("The square of Integer 7 is " & Square(7) & _

6 vbNewLine & "The square of Double 7.5 is " & Square(7.5))

7 End Sub ' Main

8 9 ' method Square takes an Integer and returns an Integer

10 Function Square(ByVal value As Integer) As Integer 11 Return Convert.ToInt32(value ^ 2) 12 End Function ' Square 12 End Function Square

13

Fig. 7.19 | Using overloaded methods. (Part 1 of 2.)

2009 Pearson Education, Inc. All rights reserved.

Page 95: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

95Outline

14 ' method Square takes a Double and returns a Double 15 Function Square(ByVal value As Double) As Double

Overload.vb

(2 of 2 )q ( y )

16 Return value ^ 2 17 End Function ' Square 18 End Module ' Overload

The square of Integer 7 is 49 The square of Integer 7 is 49

The square of Double 7.5 is 56.25

Fig. 7.19 | Using overloaded methods. (Part 2 of 2.)

Good Programming Practice 7.3O l di h d h f l lOverloading methods that perform closely related tasks can make programs clearer.

2009 Pearson Education, Inc. All rights reserved.

Page 96: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

96

7.17 Method Overloading (Cont.)

• Overload resolution determines which method to callcall.

– This process first finds methods that could be used. – Visual Basic converts variables as necessary when they areVisual Basic converts variables as necessary when they are

passed as arguments.– The compiler selects the closest match.

2009 Pearson Education, Inc. All rights reserved.

Page 97: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

97Outline

The program in Fig. 7.20 illustrates the

Overload2.vb

(1 of 2 )

The program in Fig 7 20 illustrates the syntaxerror that is generated when two methods havethe same signature and different return types. 1 ' Fig. 7.20: Overload2.vb

2 ' Using overloaded methods with identical signatures and

3 ' different return types.

4 Module Overload2

5 Sub Main() ' call Square methods with Integer and Double

the same signature and different return types.

() q g

6 Console.WriteLine("The square of Integer 7 is " & Square(7) & _

7 vbNewLine & "The square of Double 7.5 is " & Square(7.5))

8 End Sub ' Main

9 10 ' method takes a Double and returns an Integer 10 method takes a Double and returns an Integer

11 Function Square(ByVal value As Double) As Integer 12 Return Convert.ToInt32(value ^ 2) 13 End Function ' Square 14

Fig. 7.20 | Syntax error generated from overloaded methods with identical parameter lists and different return types. (Part 1 of 2.)

2009 Pearson Education, Inc. All rights reserved.

Page 98: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

98Outline

15 ' method takes a Double and returns a Double 16 Function Square(ByVal value As Double) As Double 17 Return value ^ 2 18 End Function ' Square

Overload2.vb

(2 of 2 )q

19 End Module ' Overload2

Common Programming Error 7 9

Fig. 7.20 | Syntax error generated from overloaded methods with identical parameter lists and different return types. (Part 2 of 2.)

Common Programming Error 7.9Creating overloaded methods with identical parameter lists and different return types is a compilation error.

2009 Pearson Education, Inc. All rights reserved.

yp p

Page 99: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

99

7.18 Optional Parameters

• Optional parameters specify a default value that is assigned to the parameter if that argument is not g p gpassed.

Sub ExampleMethod(ByVal value1 As Boolean, _O ti l B V l l 2 A I t 0)Optional ByVal value2 As Integer = 0)

B th f th ll t ExampleMethod lid• Both of these calls to ExampleMethod are valid:ExampleMethod(True)

ExampleMethod(False 10)ExampleMethod(False, 10)

2009 Pearson Education, Inc. All rights reserved.

Page 100: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

100

7.18 Optional Parameters (Cont.)

Common Programming Error 7.10Common Programming Error 7.10Declaring a non-Optional parameter to the rightof an Optional parameter is a syntax error.

Common Programming Error 7.11

p p y

Not specifying a default value for an Optionalparameter is a syntax error.

2009 Pearson Education, Inc. All rights reserved.

Page 101: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

101Outline

• The example in Fig. 7.21 demonstrates the useof optional parameters.

1 ' Fig 7.21: Power.vb

2 ' Optional argument demonstration with method Power.

3 Public Class Power

Power.vb

(1 of 3 )

p p

4 ' reads input and displays result

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

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

7 8 Dim value As Integer 8 Dim value As Integer

9 10 ' call version of Power depending on power input 11 If Not String.IsNullOrEmpty(powerTextBox.Text) Then 12 value = Power(Convert.ToInt32(baseTextBox.Text), _ 13 Convert ToInt32(powerTextBox Text))

Using values from both TextBoxes.13 Convert.ToInt32(powerTextBox.Text))

14 Else 15 value = Power(Convert.ToInt32(baseTextBox.Text)) 16 powerTextBox.Text = Convert.ToString(2) 17 End If

both TextBoxes.

Using the value of one TextBox and omitting the optional

18 19 outputLabel.Text = Convert.ToString(value) 20 End Sub ' calculateButton_Click

pparameter.

Fig 7 21 | Optional argument demonstration with

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.21 | Optional argument demonstration withmethod Power. (Part 1 of 3.)

Page 102: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

102

21

Outline

22 ' use iteration to calculate power 23 Function Power(ByVal base As Integer, _ 24 Optional ByVal exponent As Integer = 2) As Integer 25 26 Dim total As Integer = 1 ' initialize total

Power.vb

(2 of 3 )26 Dim total As Integer = 1 initialize total

27 28 For i = 1 To exponent ' calculate power 29 total *= base 30 Next

Using values from both TextBoxes.

31 32 Return total ' return result 33 End Function ' Power 34 End Class ' Power

baseTextBox powerTextBox

a)

base e t o powe e t o

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.21 | Optional argument demonstration withmethod Power. (Part 2 of 3.)

Page 103: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

103Outline

Power.vb

(3 of 3 )b)

Power not necessary, optional parameter

c))

calculateButton

Fig. 7.21 | Optional argument demonstration withmethod Power (Part 3 of 3 )

2009 Pearson Education, Inc. All rights reserved.

method Power. (Part 3 of 3.)

Page 104: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

104

7.19 Recursion

• A recursive method calls itself either directly or indirectlyindirectly.

• Recursive problem-solving approaches have a number of elements in common:of elements in common:

– The method solves only the simplest case—the base case.– When presented with a more complicated problem, the methodWhen 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.

2009 Pearson Education, Inc. All rights reserved.

Page 105: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

105

7.19 Recursion (Cont.)

Determining a Factorial Value Recursively• The factorial of a nonnegative integer n, written n!

(and read “n factorial”), is the productn . ( n – 1 ) . ( n – 2 ) . … . 1

• We arrive at a recursive definition of the factorial method by observing the following relationship:

n! = n . ( n – 1 )!

2009 Pearson Education, Inc. All rights reserved.

Page 106: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

106

7.19 Recursion (Cont.)• A recursive evaluation of 5! would proceed as in

Fig. 7.22.g

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.22 | Recursive evaluation of 5!.

Page 107: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

107Outline

• Figure 7.23 recursively calculates and prints factorials.

FactorialCalculator.vb

(1 of 2 )

• If number is less than or equal to 1, Factorial returns1 and the method returns.

• If number is greater than 1, the answer is expressed as

1 ' Fig. 7.23: FactorialCalculator.vb

2 ' Calculating factorials using recursion.

3 Public Class FactorialCalculator

4 ' calculate factorial

(1 of 2 )the product of number and a recursive call to Factorial.

4 calculate factorial

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

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

7 8 ' convert text in TextBox to Integer

9 Dim value As Integer = Convert.ToInt32(inputTextBox.Text)

10 displayTextBox.Clear() ' reset TextBox 11 12 ' call Factorial to perform calculation 13 For i = 0 To value 14 displayTextBox.Text &= i & "! = " & Factorial(i) & vbNewLine 15 Next 16 End Sub ' calculateButton_Click 17

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.23 | Recursive factorial program. (Part 1 of 2.)

Page 108: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

108Outline

18 ' recursively generates factorial of number 19 Function Factorial(ByVal number As Long) As Long 20 If number <= 1 Then ' base case 21 Return 1 22 Else

FactorialCalculator.vb

(2 of 2 )23 Return number * Factorial(number - 1) 24 End If 25 End Function ' Factorial 26 End Class ' FactorialCalculator

(2 of 2 )

Determining if the factorial has been resolved to its simplest pform.Factorial makes recursive calls.

Fi 7 23 | R i f t i l (P t 2 f 2 )

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.23 | Recursive factorial program. (Part 2 of 2.)

Page 109: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

109

7.19 Recursion (Cont.)

• Set the output TextBox’s ScrollBars propertyto Vertical to display more outputsto Vertical to display more outputs.

• Type Long is designed to store integer values in a range much larger than that of type Integerrange much larger than that of type Integer(such as factorials greater than 12!).

• The TextBox’s Clear method clears the text• The TextBox s Clear method clears the text.

Common Programming Error 7.12Forgetting to return a value from a recursive methodcan result in logic errors.

2009 Pearson Education, Inc. All rights reserved.

Page 110: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

110

7.19 Recursion (Cont.)

Common Programming Error 7.13Omitting 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 isinfinite recursion, eventually exhausting memory. This is analogous to the problem of an infinite loop in an iterative (nonrecursive) solution.

2009 Pearson Education, Inc. All rights reserved.

Page 111: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

111

7.20 (Optional) Software Engineering Case Study: Identifying Class OperationsCase 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 classesin our ATM system by examining the verbs and verb phrases in the requirements document (Fig. 7.24).

2009 Pearson Education, Inc. All rights reserved.

Page 112: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

112

7.20 (Optional) Software Engineering Case Study: Identifying Class OperationsCase Study: Identifying Class Operations in the ATM System (Cont.)

Class Verbs and verb phrases Class Verbs and verb phrases ATM executes financial transactions

BalanceInquiry [none in the requirements document]

Withdrawal [none in the requirements document] Withdrawal [none in the requirements document]

Deposit [none in the requirements document]

BankDatabase authenticates a user, retrieves an account balance, credits an account by a deposit amount, debits an account by a withdrawal amount

Account retrieves an account balance, credits an account by a deposit amount, debits an account by a withdrawal amount

Screen displays a message to the user

Keypad receives numeric input from the user Keypad receives numeric input from the user

CashDispenser dispenses cash, indicates whether it contains enough cash to satisfy a withdrawal request

DepositSlot receives a deposit envelope

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.24 | Verbs and verb phrases for each class in the ATM system.

Page 113: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

113

7.20 (Optional) Software Engineering Case Study: Identifying Class OperationsCase Study: Identifying Class Operations in the ATM System (Cont.)

Th UML i ( hi h• The UML represents operations (which are implemented as methods) as follows:

operationName( parameter1 parameter2 parameterN ) : returnTypeoperationName( parameter1, parameter2, … , parameterN ) : returnType

• Each parameter consists of a parameter name and type:• Each parameter consists of a parameter name and type:parameterName : parameterType

2009 Pearson Education, Inc. All rights reserved.

Page 114: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

114

7.20 (Optional) Software Engineering Case Study: Identifying Class OperationsCase Study: Identifying Class Operations in the ATM System (Cont.)

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.25 | Classes in the ATM system with attributes and operations.

Page 115: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

115

7.20 (Optional) Software Engineering Case Study: Identifying Class Operations in theStudy: Identifying Class Operations in the ATM System (Cont.)

Fig. 7.26 | Class BankDatabase with operation parameters. g | p p

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.27 | Class Account with operation parameters.

Page 116: Methods: AMethods: A Deeper Lookpersonal.kent.edu/~asamba/tech46330/Chap07.pdf7.2 Modules, Classes and Methods (Cont.) Software Engineering Observation 7 1Software Engineering Observation

116

7.20 (Optional) Software Engineering Case Study: Identifying Class OperationsCase Study: Identifying Class Operations in the ATM System (Cont.)

Fig. 7.28 | Class Screen with an operation parameters.

2009 Pearson Education, Inc. All rights reserved.

Fig. 7.29 | Class CashDispenser with operation parameters.


Recommended