
Reusing Code with Methods
Sometimes a program needs to perform the same action in several places. For example, suppose
you’re 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 menu’s Exit command, or click the X in
the program’s upper-right corner, or open the window’s 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 ca