Reusing Code with Methods
Sometimes a program needs to perform the same action in several places. For example, suppose
youre using a simple editor such as WordPad, you make some changes, and then you select the
File menu’s New command. The program realizes that you have unsaved changes and asks if
you want to save them. Depending on whether you click Yes, No, or Cancel, the program saves
the changes, discards the changes, or cancels the attempt to create a new file.
Now think about what happens when you try to open a file while you have unsaved changes.
The program goes through basically the same steps, asking if you want to save the changes. It
does practically the same thing if you select the File menus Exit command, or click the X in
the programs upper-right corner, or open the windows system menu and select Close, or press
[Alt]+F4. In all of these cases, the program performs basically the same checks.
Instead of repeating code to handle unsaved changes everywhere it might be needed, it would
be nice if you could centralize the code in a single location and then invoke that code when
you need it. In fact, you can do exactly that by using methods.
A method is a group of programming statements wrapped in a neat package so you can
invoke it as needed. A method can take parameters that the calling code can use to give it
information, it can perform some actions, and then it can return a single value to pass infor-
mation back to the calling code.
In this lesson, you learn how to use methods. You learn why they are useful, how to write
them, and how to call them from other pieces of code.
METHOD ADVANTAGES
The file editing scenario described in the previous section illustrates one of the key advan-
tages to methods: code reuse. By placing commonly needed code in a single method, you
can reuse that code in many places. Clearly that saves you the effort of writing the code
several times.
20
596906c20.indd 241 4/7/10 12:33:27 PM
242
LESSON 20 Reusing Code with Methods
Much more importantly, it also saves you the trouble of debugging the code several times. Often
debugging a piece of complex code takes much longer than typing in the code in the first place, so
being able to debug the code in only one place can save you a lot of time.
Reusing code also greatly simplifies maintenance. If you later find a bug in the code, you only need
to fix it in one place. If you had several copies of the code scattered around, youd need to fix each
one individually and make sure all of the fixes were the same. That may sound easy enough, but
making synchronized changes is actually pretty hard, particularly for larger projects. It’s just too
easy to miss one change or to make slightly different changes that later cause big problems.
Methods can sometimes make finding and fixing bugs much easier. For example, suppose you’re
working on an inventory program that can remove items from inventory for one of many reasons:
external sales, internal sales, ownership transfer, spoilage, and so forth. Unfortunately the program
occasionally “removes” items that dont exist, leaving you with negative inventory. If the program
has code in many places that can remove items from inventory, figuring out which place is causing
the problem can be tricky. If all of the code uses the same method to remove items, you can set break-
points inside that single method to see what’s going wrong. When you see the problem occurring, you
can trace the program’s flow to see where the problem originated.
A final set of advantages to using methods makes the pieces of the program easier to understand and
use. Breaking a complex calculation into a series of simpler method calls can make the code easier to
understand. No one can keep all of the details of a large program in mind all at once. Breaking the
program into methods makes it possible to understand the pieces separately.
A well-designed method also encapsulates an activity at an abstract level so other developers don’t
need to know the details. For example, you could write a
FindItemForPurchase method that searches
through a database of vendors to find the best possible deal on a particular item. Now developers writ-
ing other parts of the program can call that method without needing to understand exactly how the
search works. The method might perform an amazingly complex search to minimize price and long-
term expected maintenance costs but the programmer calling the method doesn’t need to know or care
how it works.
In summary, some of the key benefits to using methods are:
Code reuse
You write the code once and use it many times.
Centralized debugging
You only need to debug the shared code once.
Centralized maintenance
If you need to fix the code, you only need to do so in the method,
not everywhere it is used.
Problem decomposition
Methods can break complex problems into simple pieces.
Encapsulation
The method can hide complex details from developers.
METHOD SYNTAX
In C#, all methods must be part of some class. In many simple programs, the main form contains all
of the program’s code, including all of its methods.
596906c20.indd 242 4/7/10 12:33:27 PM
Method Syntax
243
The syntax for defining a method is:
accessibility returnType methodName(parameters)
{
...statements...
return returnValue;
}
Where:
accessibility
This is an accessibility keyword such as public or private. This keyword
determines what other code in the project can invoke the method.
returnType
This is the data type that the method returns. It can take normal values such
as
int, bool, or string. It can also take the special value void to indicate that the method
won’t return a result to the calling code.
methodName
This is the name that you want to give the method. You can give the method
any valid name. Valid names must start with a letter or underscore and include letters, under-
scores, and numbers. A valid name also cannot be a keyword such as
if or while.
parameters
This is an optional parameter list that you can pass to the method. I’ll say
more about this shortly.
statements
These are the statements that the method should execute.
returnValue
To return a value to the calling code, the method should execute a return
statement, passing it whatever value the method should return. Use
return without a parameter
to return from a
void method.
You can use the return statement as many times as you like in a method (for
example, after different branches in an
if-else structure). The C# compiler
tries to guarantee that all paths through the code end at a
return statement and
will warn you if the code might not return a value.
The method’s parameters allow calling code to pass information into the method. The parameters in
the method’s declaration give names to the parameters while they are in use inside the method.
For example, recall the definition of the factorial function. The factorial of a number N is written N!
and pronounced N factorial. The definition of N! is 1 * 2 * 3 * ... * N.
The following C# code implements the factorial method:
// Return value!
private long Factorial(long value)
{
long result = 1;
for (long i = 2; i <= value; i++)
{
result *= i;
}
596906c20.indd 243 4/7/10 12:33:27 PM
244
LESSON 20 Reusing Code with Methods
return result;
}
The method is declared private so only code within this class can use it. For simple programs,
that’s all of the code anyway so this isn’t an issue.
The method’s data type is
long so it must return a value of type long.
The method’s name is
Factorial. You should try to give your methods names that are simple and
that convey the methods’ purposes so its easy to remember what they do.
The method takes a single parameter of type
long named value.
The method creates a variable
result and multiplies it by the values 2, 3, ..., value.
The method finishes by executing the
return statement, passing it the final value of result.
The following code shows how a program might call the
Factorial method:
long number = long.Parse(numberTextBox.Text);
long answer = Factorial(number);
resultTextBox.Text = answer.ToString();
This code starts by creating a long variable named number and initializing it to whatever value is in
numberTextBox.
The code then calls the
Factorial method, passing it the value number and saving the returned
result in the new
long variable named answer.
Notice that the names of the variables in the calling code (
number and answer) have no relation to
the names of the parameters and variables used inside the method (
value and result). The method’s
parameter declaration determines the names those values have while inside the method.
The code finishes by displaying the result.
A method’s parameter list can include zero, one, or more parameters separated by commas. For
example, the following code defines the method
Gcd, which returns the greatest common divisor
(GCD) of two integers. (The GCD of two integers is the largest integer that evenly divides them both.)
// Calculate GCD(a, b).
private long Gcd(long a, long b)
{
long remainder;
do
{
remainder = a % b;
if (remainder != 0)
{
a = b;
b = remainder;
}
} while (remainder > 0);
return b;
}
596906c20.indd 244 4/7/10 12:33:28 PM
Parameters by Reference
245
The following code shows how you might call the Gcd method. The code initializes two integers and
then passes them to the
Gcd method, saving the result. It then displays the two integers and their GCD.
// Get the input values.
long a = long.Parse(aTextBox.Text);
long b = long.Parse(bTextBox.Text);
// Calculate the GCD.
long result = Gcd(a, b);
// Display the result.
resultTextBox.Text = b.ToString();
PARAMETERS BY REFERENCE
Parameter lists have one more feature that’s confusing enough to deserve its own section. Parameters
can be passed to a method by value or by reference.
When you pass a parameter by value, C# makes a copy of the value and passes the copy to the method.
The method can then mess up its copy without damaging the value used by the calling code.
In contrast, when you pass a value by reference, C# passes the location of the value’s memory into
the method. If the method modifies the parameter, the value is changed in the calling code as well.
Normally values are passed by value. That’s less confusing because changes that are hidden inside
the method cannot confuse the calling code.
Sometimes, however, you may want to pass a parameter by reference. To do that, add the keyword
ref before the parameter’s declaration.
To tell C# that you understand that a parameter is being passed by reference and that it’s not
just a terrible mistake, you must also add the keyword
ref before the value you are passing into
the method.
For example, suppose you want to write a method named
GetMatchup that selects two chess players
to play against each other. The method should return
true if it can find a match and false if no other
matches are possible (because you’ve played them all). The method can only return one value (
true or
false) so it must find another way to return the two players.
The following code shows how the method might be structured:
private bool
GetMatchup(ref string player1, ref string player2)
{
// Do complicated stuff to pick an even match.
...
// Somewhere in here the code should set player1
// and player2.
...
// We found a match.
return true;
}
596906c20.indd 245 4/7/10 12:33:28 PM
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.0.91