Creating Methods to Reuse Code

As programming has evolved, computer scientists have discovered techniques for making it easier to write and maintain programs. Most of these ideas are borrowed from the outside world and are simple. One of the most important is the notion of encapsulation, another word for grouping together (as already mentioned, computer scientists like to give complicated names to simple ideas).

For example, if somebody asked you what you did this weekend, you might reply, “I played with the kids, went shopping, and worked on the house.” You probably would not describe everything you did over the weekend. Instead, you would group several complex activities into one phrase. You would say, “I played with the kids,” without describing all the components of this behavior (which, in my house, involve loud noises, wrestling, Dad’s dressing up in at least one ridiculous outfit, and somebody in tears). All those details are wrapped up in one phrase.

Encapsulation in programming works much the same way. You take groups of instructions and put them together to make methods. These methods are things the object can do. For example, the critter can eat and play. It has Eat and Play methods to enable these behaviors. After you’ve defined a set of instructions as a method, you can refer to the name of the method, and all the code related to that name will execute.

The Song Program

To clarify the concept of encapsulation, I wrote a program that replicates a serious and weighty application of your computer’s horsepower. The Song program repeats the words to the classic children’s song This Old Man. In case it has been a while, the words (for the first couple of verses) go like this:

This old man, he played one He played knick-knack on my thumb With a knick-knack paddy-whack Give a dog a bone

This old man came rolling home This old man, he played two He played knick-knack on my shoe With a knick-knack paddy-whack Give a dog a bone This old man came rolling home

The song goes along for 10 verses, but the pattern is evident by the second stanza. You can see that most of the verses are almost the same, except that each features a number and the old man plays knick-knack (whatever that means) on something that rhymes with the number. A computerized version of the song is amazingly compact if you think of it in terms of methods.

Building the Main() Method

So far, all the programs in this book have been written entirely in the Main() method. You might be surprised to learn that the Main() method of most programs in C# is very small. Figure 4.6 demonstrates the Main() method for the Song program.

Figure 4.6. The Main() method features a few commands. You can probably guess what each one does.


Like most songs, This Old Man has a pattern: a simple verse that changes and a chorus that stays the same. You can summarize the pattern of the song like this:

verse 1

chorus

verse 2

chorus

Of course, this summary is much like the Main() method. To pull this off, I had to build methods to handle the verses and the chorus, but all the code is delegated to these methods. With the details encapsulated away in various methods, the main() method clearly demonstrates the main flow of the program.

In Figure 4.6, I utilized a feature of the .NET IDE. For this image, I wasn’t interested in the details of any methods except the main() method, so I used the small plus and minus signs along the left margin to collapse and expand the methods I wanted to look at. This is a wonderful tool because it enables you to focus on the parts of the program you’re currently working on, without losing sight of how each part fits into the larger picture.

Of course, the program won’t work exactly like this yet because it is necessary to write the methods. You do that in the next few sections.

Creating a Simple Method

You will start with the doChorus() method because it’s the most straightforward:

static void doChorus(){
  string message = "";
  message += "
…With a knick-knack paddy whack
";
  message += "Give a dog a bone
";
  message += "This old man came rolling home."; 
  message += "

";
  System.Console.WriteLine(message);
} // end doChorus

Custom methods can begin just like the main() method. I declared the method with

static void doChorus(){

The static keyword defines the method as one that can be called before the class has been completely created. It’s okay if you don’t understand that yet. The concept will make more sense after you learn about constructors and instantiation later in this chapter.

The void keyword indicates that this method will not return any value. Again, you have to take my word for it, but I’ll explain exactly what that means later in this chapter in a section cleverly called “Returning a Value.” doChorus() is the name of the method, so all the code in this section is named doChorus, and the main() method can invoke all these commands by simply calling the doChorus() method.

The code inside the method is straightforward. I created a string variable named message, added some values to it to write the chorus, and wrote that message to the screen.

Notice that you can create variables inside a method, as well as inside a class. This is important because a variable lives only as long as the structure in which it’s created. In other words, the message variable is created each time the doChorus() method is invoked, but as soon as that method finishes (which takes a fraction of a second), the message variable is destroyed. This is good because you don’t have to worry about the message variable’s interference with other code you’re writing. This local ownership of variables is called data hiding, and it’s another benefit of encapsulation.

NOTE

IN THE REAL WORLD

A long time ago I wrote a program for a middle school. The program had to be run on Apple IIe machines, so I was required to use an antiquated language that allows only two-character variable names and cannot encapsulate code. I had the program running almost perfectly, but it was doing very strange things at unpredictable intervals. After tearing out my hair for three days, I finally discovered that I had accidentally used the same variable name for two different things. This is exactly the sort of situation that encapsulation and data hiding can prevent.

Adding a Parameter

The doChorus() method is easy to write because it works exactly the same way each time you call it. However, you frequently run into situations more like the verse–you want the program to behave almost the same each time, but you want to send it a value to act upon. Many of the methods you’ve already used (such as Console.WriteLine) work in this way. They expect you to send a value between the parentheses, and then they act on that value. Notice in the main() method that, when I call the doVerse() method, I always include an integer value. It is quite easy to write a method that accepts a value:

static void doVerse(int verseNum){
  string message = "";
  message += "This old man, he played ";
  message += verseNum;
  message += ". 
He played knick-knack ";
  message += getPlace(verseNum);
  Console.WriteLine(message);
} // end verse

To modify a method so that it can accept a value, put a variable declaration inside the quotes that follow the method’s name. This special variable is called a parameter, and it automatically accepts whatever value was sent when the method was called. For example, when the main() method says doVerse(1), the value of verseNum inside doVerse() is 1. The next time the main() method invokes doVerse(2), the verseNum parameter will have the value 2. You can have as many parameters as you like, but you must indicate the type of parameter you will send, and you must separate the parameters by commas. Parameters have the same kind of limited life span as variables declared inside a method.

Notice that the doVerse() method also has a message variable, but this one is entirely unrelated to the message variable in doChorus().

In the following line, you can see how I used verseNum to integrate the verse number into the verse:

message += verseNum;

However, associating the place with each number (such as the thumb for verse 1 and the shoe for verse 2) is more complex, so I decided to ship that code to another method. Take a look at this line, and you’ll see that it’s a little different:

message += getPlace(verseNum);

This sends the value of verseNum to another method, named getPlace(), but the getPlace() method seems to work differently than doVerse() and doChorus(). It doesn’t stand on its own in a line of code, but it returns a value you can do something with. In this case, the results of the call to getPlace(verseNum) will be appended to the message variable.

Returning a Value

You can write methods that receive values through parameters and methods that send values through a return statement. The Console.ReadLine() method is probably the classic example of the latter kind of method. You can usually spot methods that return a value by the way they are used. The new value is usually printed to the screen or assigned to a variable. Methods that don’t return a value are usually used in a line of code by themselves, such as doChorus(). I designed the getNumber() method so that it will accept a parameter (the verse number) and return the associated place. Here’s how it works:

string message = "";
  switch (verseNum){
    case 1:
      message = "on my thumb ";
      break;
    case 2:
      message = "on my shoe ";
      break;
    default:
      message = "not yet defined";
      break;
  } // end switch
  return message;
} // end getPlace

The code works as a simple switch statement. The message variable (again, unrelated to the other message variables because it’s defined locally in a method) gets some value based on the verse number. The value of message is returned in the last line of the method. Any code that invokes this method will receive the value of message.

Use the F11 key trick to watch the flow of code through this program. It’s very important to see how the logic flows between methods. Mastering this trick is the key to building more complex programs successfully.

Figure 4.7 illustrates the output of the song as produced by the Song program.

Figure 4.7. The Song program re-creates the song This Old Man.


..................Content has been hidden....................

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