Lesson 20
Reusing Code with Methods
Sometimes a program needs to perform the same action in several places. For example, consider the UFO shooting gallery game you wrote for Exercise 19-12 and shown in Figure 20.1.
When a laser bolt hits a UFO, the program takes these steps:
- Plays the “hit a UFO” sound effect.
- Increases the player's score and shows it in the score
Label
. - Hides the laser bolt
PictureBox
. - Sets
BoltIsAway = false
to remember that no laser bolt is currently on the form. - If that was the player's last laser bolt:
- Plays the “game over” sound effect.
- Displays the “game over” label showing the player's final score.
- Disables the
Timer
. - If the player's score is greater than the smallest high score:
- Creates a
NewHighScoreForm
. - Places the player's score on the
NewHighScoreForm
. - Displays the
NewHighScoreForm
. - If the user enters a name and clicks OK:
- Replaces the lowest high score with the player's current score.
- Sorts the high scores.
- Creates a new
HighScoreForm
. - Places the high scores on the
HighScoreForm
. - Displays the
HighScoreForm
.
- Creates a
Now suppose a laser bolt moves off the top edge of the form without hitting a UFO. In that case the program must perform the same steps 3 through 5. The way I wrote my program, those steps take 33 lines of code (not counting blank lines and comments). That's a lot of repeated code to write, debug, and maintain.
In fact, ...
Get C# 24-Hour Trainer, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.