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.

Screenshot of Ufo window with three UFOs atop and six rectangular objects at the bottom left corner of the window. Another rectangular object is above an inverted T-shaped object.

Figure 20.1

When a laser bolt hits a UFO, the program takes these steps:

  1. Plays the “hit a UFO” sound effect.
  2. Increases the player's score and shows it in the score Label.
  3. Hides the laser bolt PictureBox.
  4. Sets BoltIsAway = false to remember that no laser bolt is currently on the form.
  5. If that was the player's last laser bolt:
    1. Plays the “game over” sound effect.
    2. Displays the “game over” label showing the player's final score.
    3. Disables the Timer.
    4. If the player's score is greater than the smallest high score:
      1. Creates a NewHighScoreForm.
      2. Places the player's score on the NewHighScoreForm.
      3. Displays the NewHighScoreForm.
      4. If the user enters a name and clicks OK:
        1. Replaces the lowest high score with the player's current score.
        2. Sorts the high scores.
        3. Creates a new HighScoreForm.
        4. Places the high scores on the HighScoreForm.
        5. Displays the HighScoreForm.

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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.