Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft CSharp Programming For The Absolute Beginner (2002) [eng]-1.pdf
Скачиваний:
46
Добавлен:
16.08.2013
Размер:
15.71 Mб
Скачать

Figure 4.5: The cost of neglect can be a sad and lifeless critter. Fortunately, with enough food and love, it can be revived.

I used simple rules to drive the critter’s behavior. During each turn, the critter ages and becomes hungrier and a little more unhappy. Whenever you talk to the critter, it gives you a message based on its current happiness level. If the critter is hungry, it becomes unhappy even more quickly. Playing with and feeding the critter make it happier. That’s all there is to the design of the critter, but to create the program, I relied on OOP techniques. The critter is actually an object, and it can talk, eat, play, and age.

Another interesting feature of the Critter program is the use of a simple menu. Many console−based programs use a menu, so now you’ll learn how to build one.

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

80

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:

81

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.

Trick 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 += "\n...With a knick−knack paddy whack\n"; message += "Give a dog a bone\n";

message += "This old man came rolling home."; message += "\n\n"; 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

82

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.

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 += ". \nHe 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;

83

Соседние файлы в предмете Программирование на C++