Presentation is loading. Please wait.

Presentation is loading. Please wait.

7 Methods: A Deeper Look.

Similar presentations


Presentation on theme: "7 Methods: A Deeper Look."— Presentation transcript:

1 7 Methods: A Deeper Look

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

3 O! call back yesterday, bid time return.
William Shakespeare Answer me in one word. There is a point at which methods devour themselves. Frantz Fanon

4 OBJECTIVES In this chapter you will learn:
To construct programs modularly from methods. That Shared methods are associated with a class rather than a specific instance of the class. To use common Mat methods from the Framework Class Library. To create new methods. The mechanisms used to pass information between methods. Simulation techniques that employ random number generation. How the visibility of identifiers is limited to specific regions of programs. To write and use recursive methods (methods that call themselves).

5 7.1   Introduction 7.2   Modules, Classes and Methods 7.3   Subroutines: Methods That Do Not Return a Value 7.4   Functions: Methods That Return a Value 7.5   Shared Methods and Class Math 7.6   GradeBook Case Study: Declaring Methods with Multiple Parameters 7.7   Notes on Declaring and Using Methods 7.8   Method Call Stack and Activation Records 7.9   Implicit Argument Conversions 7.10   Option Strict and Data-Type Conversions 7.11   Value Types and Reference Types 7.12   Framework Class Library Namespaces

6 7.13   Passing Arguments: Pass-by-Value vs. Pass-by-Reference
7.14   Scope of Declarations 7.15   Case Study: Random Number Generation 7.16   Case Study: A Game of Chance 7.17   Method Overloading 7.18   Optional Parameters 7.19   Recursion 7.20   (Optional) Software Engineering Case Study: Identifying Class Operations in the ATM System 7.21   Wrap-Up

7 7.1 Introduction Divide and conquer technique
Construct a large program from smaller pieces Can be accomplished using methods Shared methods can be called without the need for an object of the class Random number generation Method overloading Recursion

8 7.2 Modules, Classes and Methods
Programs consists of many pieces: Modules and classes which are composed of smaller pieces: Methods 2 types of methods Subroutines Functions Several motivations for diving code into methods Makes program development more manageable Software reusability Avoid repeating code

9 Software Engineering Observation 7.1
When possible, use .NET Framework classes and methods instead of writing new classes and methods. This reduces program development time and can prevent the introduction of errors.

10 Performance Tip 7.1 .NET Framework Class Library methods are written to perform efficiently.

11 Software Engineering Observation 7.2
To promote reusability, the capabilities of each method should be limited to the performance of a single, well-defined task, and the name of the method should express that task effectively.

12 Software Engineering Observation 7.3
If you cannot choose a concise method name that expresses the task performed by a method, the method could be attempting to perform too many diverse tasks. Consider dividing such a method into several smaller methods.

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

14 7.3 Subroutines: Methods That Do Not Return a Value
Methods that perform a task but does not return a value Format: Sub method-name(parameter-list) declarations and statements End Sub

15 Outline Pass in arguments to calculate and print out payment amount
Payment.vb Pass in arguments to calculate and print out payment amount Subroutine header Print out payment using the currency specifier

16 Common Programming Error 7.1
Declaring a variable in the method’s body with the same name as a parameter variable in the method header is a compilation error.

17 Error-Prevention Tip 7.1 Although it is allowable, an argument passed to a method should not have the same name as the corresponding parameter name in the method declaration. This prevents ambiguity that could lead to logic errors.

18 Software Engineering Observation 7.4
Method names tend to be verbs because methods typically perform actions. By convention, method names begin with an uppercase first letter. For example, a method that sends an message might be named SendMail.

19 Error-Prevention Tip 7.2 Small methods are easier to test, debug and understand than large methods.

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

21 7.4 Functions: Methods That Return a Value
Methods that return a value to the caller Format: Function method-name(parameter-list) As return-type declarations and statements End Function Return statement Terminates execution of the method and returns the value Can occur anywhere in method

22 Outline Function call Return the square of the argument as an Integer
SquareInteger.vb Function call Return the square of the argument as an Integer

23 Common Programming Error 7.2
If the expression in a Return statement cannot be converted to the function’s return-type, a runtime error is generated.

24 Common Programming Error 7.3
Failure to return a value from a function (e.g., by forgetting to provide a Return statement) causes the function to return the default value for the return-type, possibly producing incorrect output.

25 7.5 Shared Methods and Class Math
Shared method (or class method) Applies to the class as a whole instead of a specific object of the class Call a Shared method by using the method call: ClassName.methodName( arguments ) All methods of the Math class are Shared example: Math.Sqrt( ) All methods in a Module is implicitly Shared

26 Software Engineering Observation 7.5
It is not necessary to add an assembly reference to use the Math class methods in a program, because class Math is located in namespace System, which is implicitly added to all .NET applications.

27 7.5 Shared Methods and Class Math (Cont.)
Constants Keyword Const Cannot be changed after initialization Implicitly Shared; syntax error when explicitly declared Fields (or class variables) Shared variables and instance variables Math.PI and Math.E are Const Shared fields of the Math class

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

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

30 7.6 GradeBook Case Study: Declaring Methods with Multiple Parameters
Multiple parameters can be declared by specifying a comma-separated list. Arguments passed in a method call must be consistent with the number, types and order of the parameters Sometimes called formal parameters

31 Outline GradeBook.vb (1 of 4 )

32 Outline (2 of 4 ) Prompt the user to enter and read three values
GradeBook.vb (2 of 4 ) Prompt the user to enter and read three values

33 Outline Call method Maximum (3 of 4 )
GradeBook.vb (3 of 4 ) Declare the Maximum method with multiple parameters Compare y and maximumValue Compare z and maximumValue

34 Outline Return the maximum value (4 of 4 ) Display maximum value
GradeBook.vb (4 of 4 ) Display maximum value

35 Outline Create a GradeBook object (1 of 2 )
GradeBookTest.vb (1 of 2 ) Call DisplayGradeReport method

36 Outline GradeBookTest.vb (2 of 2 )

37 7.6 GradeBook Case Study: Declaring Methods with Multiple Parameters (Cont.)
Reusing method Math.Max The expression Math.Max( x, Math.Max( y, z ) ) determines the maximum of y and z, and then determines the maximum of x and that value

38 7.7 Notes on Declaring and Using Methods
Three ways to call a method: Use a method name by itself to call another method of the same class or module Use a variable containing a reference to an object, followed by a dot (.) and the method name to call a method of the referenced object Use the class or module name and a dot (.) to call a Shared method of a class Shared methods cannot call non-Shared methods of the same class directly

39 7.7 Notes on Declaring and Using Methods (Cont.)
Three ways to return control to the calling statement: If method does not return a result: Program flow reaches the end of a method Program executes the Return statement If method does return a result: Program executes the statement Return expression expression is first evaluated and then its value is returned to the caller

40 Common Programming Error 7.4
Declaring a method outside the body of a class or module declaration or inside the body of another method is a syntax error.

41 Common Programming Error 7.5
Omitting the return-value-type in a method declaration, if that method is a function, is a syntax error.

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

43 Common Programming Error 7.7
Returning a value from a method that is a subroutine is a compilation error.

44 7.8 Method Call Stack and Activation Records
Stacks Last-in, first-out (LIFO) data structures Items are pushed (inserted) onto the top Items are popped (removed) from the top Program execution stack Also known as the method call stack Return addresses of calling methods are pushed onto this stack when they call other methods and popped off when control returns to them

45 7.8 Method Call Stack and Activation Records (Cont.)
A method’s local variables are stored in a portion of this stack known as the method’s activation record or stack frame When the last variable referencing a certain object is popped off this stack, that object is no longer accessible by the program Will eventually be deleted from memory during “garbage collection” Stack overflow occurs when the stack cannot allocate enough space for a method’s activation record

46 7.9 Implicit Argument Conversions
Converting an argument’s value to a type that the method expects to receive in its corresponding parameter Visual Basic support widening and narrowing conversions Widening occurs when an argument is converted to a parameter of another type that can hold more data Narrowing occurs when there is a potential for data loss during the conversion Visual Basic perform widening and narrowing conversion on arguments pass to methods Some implicit narrowing may cause runtime errors Values in an expression are converted to the “widest” type in the expression (a temporary copy of the value is made)

47 Fig. 7. 7 | Widening conversions between primitive types. (Part 1 of 2

48 Fig. 7. 7 | Widening conversions between primitive types. (Part 2 of 2

49 Common Programming Error 7.8
Converting a primitive-type value to a value of another primitive type may change the value if the conversion is not a widening conversion. For example, converting a floating-point value to an integral value truncates any fractional part of the floating-point value (e.g., 4.7 becomes 4).

50 7.10 Option Strict and Data-Type Conversions
Visual Basic provides several options for controlling the way the complier handles types Option Explicit On by default Forces you to explicitly declare all variables before they are used in program Less errors Option Strict Off default When On, the complier check all conversions that could cause data loss or program termination Increase program clarity and debugging time Class Object is the base type of all types in Visual Basic

51 Fig. 7.8 | Modifying Option Strict and Option Explicit.

52 7.10 Option Strict and Data-Type Conversions (Cont.)
An explicit conversion uses a cast operator for method to force a conversion to occur Class Convert The name of each conversion method is the word To, followed by the name of the type to which the method converts its argument Ex: Convert.ToDouble(Console.ReadLine()) Many primitive types have a Parse method they can use for conversion

53 Error-Prevention Tip 7.3 From this point forward, all code examples have Option Strict set to On.

54 7.11 Value Types and Reference Types
In Visual Basic, everything can be categorize as 2 types: Value Data of that type Most primitive types Structures and enumerations Reference Address of the location in memory where the data referred to by that variable is stored Classes, modules, interfaces and delegates String is the only primitive reference type

55 Fig. 7.9 | Primitive types. (Part 1 of 2.)

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

57 7.12 Framework Class Library Namespace
.NET Framework Class Library Collection of namespaces Groups of related predefined classes .NET Documentation Help > Index MSDN

58 Fig. 7.10 | FCL namespaces (a subset). (Part 1 of 2.)

59 Fig. 7.10 | FCL namespaces (a subset). (Part 2 of 2.)

60 Good Programming Practice 7.2
The Visual Studio .NET documentation is easy to search and provides many details about each class. As you learn a class in this book, you should read about the class in the online documentation.

61 7.14 Passing Arguments: Pass-by-Value vs. Pass-by-Reference
Argument pass by value Copy of value is made and passed into the function Changes to the copy does not affect the original value (unless it is a reference type) Keyword ByVal Argument pass by reference Gives the method the ability to access and modify original variable Objects always passed by reference Keyword ByRef

62 Outline (1 of 3 ) Method call passing number1 by value
ByRefTest.vb (1 of 3 ) Method call passing number1 by value Method call passing number2 by reference

63 Outline (2 of 3 ) Method call passing number3 by value
ByRefTest.vb (2 of 3 ) Method call passing number3 by value Changes are not saved to original variable Changes are saved to original variable

64 Outline ByRefTest.vb (3 of 3 )

65 Error-Prevention Tip 7.4 When passing arguments by value, changes to the called method’s copy do not affect the original variable’s value. This prevents possible side effects that could hinder the development of correct and reliable software systems. Always pass value-type arguments by value unless you explicitly intend for the called method to modify the caller’s data.

66 7.14 Scope of Declarations Basic scope rules Block scope Method scope
The scope of a variable declared in a block is from the point of the declaration to the end of the block Method scope The scope of a method’s local-variable declaration or parameter is from the point at which the declaration appears to the end of that method Module scope The scope of a class’s or module’s members is that entire body of the class or module All modules members are implicitly Shared, so all methods of a module can access all variables and other methods of the module Namespace scope Elements declared in a namespace are accessible to all other elements in the same namespace By default, all elements of a project are part of a namespace that uses the project’s name Shadowing: A local variable or parameter in a method that has the same name as a field of a class is hidden until the block terminates execution

67 Error-Prevention Tip 7.5 Use different names for fields and local variables to help prevent subtle logic errors that occur when a method is called and a local variable of the method shadows a field of the same name in the class.

68 Outline (1 of 2 ) Shadows field x Display value of local variable x
Scope.vb (1 of 2 ) Shadows field x Display value of local variable x

69 Outline Shadows field x (2 of 2 ) Display value of local variable x
Scope.vb (2 of 2 ) Display value of local variable x Display value of field x

70 Outline ScopeTest.vb

71 7.15 Case Study: Random-Number Generation
Class Random Random’s Next method generates a random Integer value in the range 0 to +2,147,483,646, inclusive Scaling: With one Integer argument, Next returns a value from 0 up to, but not including, the argument’s value Shifting: With two Integer argument, Next returns a value from the lower Integer up to, but not including, the higher Integer Equal likelihood Class Random from System namespace Is seeded with the current time of day to generate different sequences of numbers each time the program executes

72 Outline Create a Random object Generate random numbers 1-5 for the die
RandomInteger.vb Generate random numbers 1-5 for the die

73 Outline Using the IO capabilities from the FCL (1 of 2 )
RollDice.vb (1 of 2 ) Create a Random object

74 Outline Assigning a random number 1-6 to face (2 of 2 )
RollDice.vb (2 of 2 ) Load the image corresponding to face

75 Fig. 7.16 | Imported namespaces in a project.

76 Outline Create a Random object (1 of 4 )
RollTwelveDice .vb (1 of 4 ) Variables to count frequency of die

77 Outline (2 of 4 ) Output results using the percentage format specifier
RollTwelveDice .vb (2 of 4 ) Output results using the percentage format specifier

78 Outline RollTwelveDice .vb (3 of 4 ) Select…Case based on the die roll to determine frequency

79 Outline RollTwelveDice .vb (4 of 4 )

80 7.16 Case Study: A Game of Chance
Enumerations Programmer-declared types consisting of sets of constants Enum keyword A type name (e.g. Status) Enumeration constants (e.g. WON, LOST and CONTINUE) To compare simple-type value to underlying value of an enumeration, you must typecast for the two types to match

81 Outline (1 of 4 ) Declare an enumeration Create a Random object
CrapsGame.vb (1 of 4 ) Declare an enumeration Create a Random object

82 Outline Call RollDice method (2 of 4 )
CrapsGame.vb (2 of 4 ) Player wins with a roll of 7 or 11 Player loses with a roll of 2, 3 or 12 Set and display the point

83 Outline Call RollDice method (3 of 4 ) Player wins by making the point
CrapsGame.vb (3 of 4 ) Player wins by making the point Player loses by rolling 7

84 Outline Declare RollDice method (4 of 4 ) Generate two dice rolls
CrapsGame.vb (4 of 4 ) Generate two dice rolls

85 7.17 Method Overloading Method Overloading
Multiple methods with the same name, but different types, number or order of parameters in their parameter lists Compiler decides which method is being called by matching the method call’s argument list to one of the overloaded methods’ parameter lists A method’s name and number, type and order of its parameters form its signature Differences in return type are irrelevant in method overloading Overloaded methods can have different return types Methods with different return types but the same signature cause a compilation error

86 Good Programming Practice 7.3
Overloading methods that perform closely related tasks can make programs clearer.

87 Outline Overload2.vb Same method signature Compilation error

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

89 7.18 Optional Parameters Methods can have optional parameters
Optional parameters must specify a default value that is assigned to the parameter if the optional argument is not passed There can be more than one optional parameters All optional parameters must be placed to the right of the method’s non-optional parameters Optional parameters are specified in the method header with keyword Optional

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

91 Common Programming Error 7.11
Not specifying a default value for an Optional parameter is a syntax error.

92 Outline (1 of 2 ) Method call does provides the optional parameter
Power.vb (1 of 2 ) Method call does provides the optional parameter Method call does not provide the optional parameter Default value of the optional parameter is 2

93 Outline Power.vb (2 of 2 )

94 7.19 Recursion Recursion A method that calls itself
Break the problem you want to solve into pieces Recursive method consists of: Base case(s) Solving simple problem Recursive call(s) Also known as recursion step(s) Normally includes a Return statement

95 Fig. 7.21 | Recursive evaluation of 5!.

96 Outline Factorial.vb (1 of 2 ) Call recursive method

97 Outline Base case: number <= 1 (ends recursion) Recursive call
Factorial.vb (2 of 2 ) Recursive call

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

99 Common Programming Error 7.13
Omitting the base case or writing the recursion step so that it does not converge on the base case will cause infinite recursion, eventually exhausting memory. This is analogous to the problem of an infinite loop in an iterative (nonrecursive) solution.

100 7.20 (Optional) Software Engineering Case Study: Identifying Class Operations in the ATM System
Identifying operations Examine key verbs and verb phrases in the requirements document Modeling operations in UML Each operation is given an operation name, a parameter list and a return type: operationName( parameter1, parameter2, …, parameterN ) : return type Each parameter has a parameter name and a parameter type parameterName : parameterType

101 7.20 (Optional) Software Engineering Case Study: Identifying Class Operations in the ATM System (Cont.) Some operations may not have return types yet Remaining return types will be added as design and implementation proceed Identifying and modeling operation parameters Examine what data the operation requires to perform its assigned task Additional parameters may be added later on

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

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

104 Fig. 7.25 | Class BankDatabase with operation parameters.

105 Fig. 7.26 | Class Account with operation parameters.

106 Fig. 7.27 | Class Screen with an operation parameter.

107 Fig. 7.28 | Class CashDispenser with operation parameters.


Download ppt "7 Methods: A Deeper Look."

Similar presentations


Ads by Google