Title: IE 411511: Visual Programming for Industrial Applications
1IE 411/511Visual Programming for Industrial
Applications
- Lecture Notes 8
- Methods A Deeper Look
2OBJECTIVES
- In this chapter you will learn
- To construct programs modularly from methods
- That Shared methods are associated with a class
rather than a specific instance of the class - To use common Math methods from the Framework
Class Library - To create new methods
3OBJECTIVES
- The mechanisms used to pass information between
methods - How the visibility of identifiers is limited to
specific regions of programs - To write and use recursive methods(methods that
call themselves)
4Modules, Classes and Methods
- Programs consist of many pieces, including
modules and classes - Modules and classes are composed of methods,
fields and properties - You combine new modules and classes with those
available in class libraries - Related classes are grouped into namespaces
5Modules, Classes and Methods (cont.)
- A method is invoked by a method call
- The method call specifies the method name and
provides information - When the method completes its task, it returns
control to the caller - In some cases, the method also returns a result
to the caller
6Modules, Classes and Methods (cont.)
- A boss (the caller) asks a worker (the callee) to
perform a task and return the results when the
task is done - The worker might call other workers
- However, the boss would be unaware of this
7Modules, Classes and Methods (cont.)
- To promote reusability, the capabilities of each
method should be limited to the performance of a
single, well-defined task - Also, the name of the method should express that
task effectively - 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
8Modules, Classes and Methods (cont.)
- Subroutines (such as Console.WriteLine) do
notreturn a value - The console application below uses a
subroutineto print a workers payment information
9Subroutines
- Subroutines are methods that do not return a
value - The format of a subroutine declaration is
- The parameter-list is a comma-separated list of
each parameters type and name - The type of each argument must be consistent with
its corresponding parameters type - If a method does not receive any values, the
method name is followed by an empty set of
parentheses
Sub method-name(parameter-list)
Declarations and statements End Sub
10Subroutines (cont.)
- Declaring a variable in the methods body with
the same name as a parameter variable in the
method header is a compilation error - 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
11Subroutines (cont.)
- The method body (also referred to as a block)
contains declarations and statements - The body of a method declared with Sub must be
terminated with End Sub - Method names tend to be verbs because methods
typically perform actions - By convention, method names begin with an
uppercase first letter - e.g., a method that sends an e-mail message might
be named SendMail - Small methods are easier to test, debug and
understand than large methods
12Functions
- Functions are methods that return a valueto the
caller - The console application on the next slide uses
the function Square to calculate the squares of
the integers from 1 to 10
13Functions (cont.)
14Functions (cont.)
- The Return statement terminates the method and
returns the result - The return statement can occur anywhere in a
function body -
- Return expression
- The return-type indicates the type of the result
returned from the function
15Functions (cont.)
- If the expression in a Return statement cannot be
converted to the functions return-type, a
runtime error is generated - 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
16Shared Methods and Class Math
- A method which performs a task that does not
depend on an object is known as a Shared method - Place the Shared modifier before the keyword Sub
or Function - To call a Shared method, do the following
-
- ClassName.MethodName(arguments)
- Class Math provides a collection of Shared
methods - Math.Sqrt(900.0)
17Shared Methods and Class Math (cont.)
- It is not necessary to add an assembly reference
to use the Math class methods in a program,
because class Math is located in the assembly
mscorlib.dll, which is referenced by every .NET
application - Also it is not necessary to import class Maths
namespace (System), because it is implicitly
imported in all .NET applications
18Shared Methods and Class Math (cont.)
- Summary of several Math class methods (1 of 3)
- In the figure, x and y are of type Double
19Shared Methods and Class Math (cont.)
- Summary of several Math class methods (2 of 3)
- In the figure, x and y are of type Double
20Shared Methods and Class Math (cont.)
- Summary of several Math class methods (3 of 3)
- In the figure, x and y are of type Double
21Shared Methods and Class Math (cont.)
- Math.PI and Math.E are declared in class Math
with the modifiers Public and Const - Const declares a constanta value that cannot be
changed. - Constants are implicitly Shared
22Notes on Declaring and Using Methods
- There are three ways to call a method
- Using a method name by itself within the same
class or module - Using a reference to an object, followed by a dot
(.) and the method name to call a method of the
object - Using the class or module name and a dot (.) to
call a Shared method - A Shared method can call only other Shared methods
23Notes on Declaring and Using Methods
- Common Programming Errors with Methods
- Declaring a method outside the body of a class or
module declaration or inside the body of another
method is a syntax error - Omitting the return-value-type in a method
declaration, if that method is a function, is a
syntax error - Redeclaring a method parameter as a local
variable in the methods body is a compilation
error - Returning a value from a method that is a
subroutine is a compilation error
24Implicit Argument Conversion (cont.)
- An important feature of argument passing is
implicit argument conversion - A widening conversion occurs when an argument is
converted to another type that can hold more data - A narrowing conversion occurs when there is
potential for data loss during the conversion
25Implicit Argument Conversion (cont.)
- 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) - Conversions occur in expressions containing two
or more types - Temporary copies of the values are converted to
the widest type in the expression - The value of integerNumber is converted to type
Single for this operation - singleNumber integerNumber
26Implicit Argument Conversion (cont.)
- The figure below lists the widening conversions
supported by Visual Basic (1 of 2)
27Implicit Argument Conversion (cont.)
- The figure below lists the widening conversions
supported by Visual Basic (2 of 2)
28Option Strict and Data-Type Conversions
- Option Explicit forces an explicit declaration of
variables before they are used - To set Option Explicit to Off
- Double click My Project in Solution Explorer
- Click the Compile tab, then select the value Off
from the Option Explicit drop-down list
Drop-down list to modify Option Infer
Drop-down list to modify Option Strict
Compile tab
Drop-down list to Modify Option Explicit
29Option Strict and Data-Type Conversions (cont.)
- Option Strict requires explicit conversion for
all narrowing conversions - An explicit conversion uses a cast operator or a
method - The methods of class Convert explicitly convert
data from one type to another, e.g., - number Convert.ToDouble(Console.ReadLine())
30Value Types and Reference Types
- All Visual Basic types can be categorized as
either value types or reference types - A variable of a value type contains data of that
type - A variable of a reference type contains the
address of the location in memory where the data
is stored
31Value Types and Reference Types (cont.)
32Value Types and Reference Types (cont.)
33Value Types and Reference Types (cont.)
34Framework Class Library Namespaces
- The .NET framework contains many classes grouped
into over 100 namespaces - A program includes the an Imports declaration to
use classes from that namespace, e.g., -
- Imports System.Windows.Forms
35Framework Class Library Namespaces (cont.)
- Some key namespaces (1 of 2)
36Framework Class Library Namespaces (cont.)
- Some key namespaces (2 of 2)
37Passing Arguments
- Arguments are passed pass-by-value
orpass-by-reference - When an argument is passed by value, the program
makes a copy of the arguments value and passes
the copy - Changes to the copy do not affect the original
variable - When an argument is passed by reference, the
original data can be accessed and modified
directly
38Passing Arguments (cont.)
- The following program demonstrates passing
arguments by value and by reference (1 of 4)
39Passing Arguments (cont.)
- The following program demonstrates passing
arguments by value and by reference (2 of 4)
Squaring number2 by reference.
Squaring number1 by value.
The inner set of parentheses evaluates number3 to
its value and passes this value.
40Passing Arguments (cont.)
- The following program demonstrates passing
arguments by value and by reference (3 of 4)
ByVal indicates that its argument is passed by
value.
Squaring the number parameter value.
ByRef receives its parameter by reference.
Squaring the number parameters reference.
41Passing Arguments (cont.)
- The following program demonstrates passing
arguments by value and by reference (4 of 4)
42Passing Arguments (cont.)
- When passing arguments by value, changes to the
called methods copy do not affect the original
variables 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 callers data
43Scope of Declarations
- A declarations scope is the portion of the
program that can refer to the declared entity by
its name without qualification - The basic scopes are
- Block scope ? From the point of the declaration
to the end of the block - Method scope ? From the point of the declaration
to the end of that method - Module scope ? The entire body of the class or
module - Namespace scope ? Accessible to all other
elements in the same namespace
44Scope of Declarations (cont.)
- If a local variable has the same name as a field
of the class, the field is hidden - This is called shadowing
- A variables lifetime is the period during which
the variable exists in memory - Variables normally exist as long as their
container exists - Use different names for fields and local
variables - Helps 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
45Scope of Declarations (cont.)
This instance variable is shadowed by any local
variable named x.
Method Begin declares a local variable x
46Scope of Declarations (cont.)
Subroutine UseLocalVariable declares a local
variable x
Modifying the local variable x
UseInstanceVariable does not declare local
variables, so x refers to the instance variable.
47Scope of Declarations (cont.)
48Method Overloading
- Method overloading allows you to create methods
with the same name but different parameters - Overloading methods that perform closely related
tasks can make programs clearer
49Method Overloading (cont.)
- Overload resolution determines which method to
call - This process first finds methods that could be
used - Visual Basic converts variables as necessary when
they are passed as arguments - The compiler selects the closest match
- Creating overloaded methods with identical
parameter lists and different return types is a
compilation error
50Method Overloading (cont.)
51Optional Parameters
- Optional parameters specify a default value that
is assigned to the parameter if that argument is
not passed -
- Sub ExampleMethod(ByVal value1 As Boolean, _
Optional ByVal value2 As Integer 0) - Both of these calls to ExampleMethod are valid
- ExampleMethod(True)
- ExampleMethod(False, 10)
52Optional Parameters (cont.)
- Declaring a non-Optional parameter to the right
of an Optional parameter is a syntax error - Not specifying a default value for an Optional
parameter is a syntax error
53Optional Parameters (cont.)
Using values from both TextBoxes.
Using the value of one TextBox and omitting the
optional parameter.
54Optional Parameters (cont.)
Using values from both TextBoxes.
baseTextBox
powerTextBox
55Optional Parameters (cont.)
Power not necessary, optional parameter
calculateButton