chapter six

6 Functions

 

Functions are one of the cornerstones of programming---but not because there is a technical need for them. We could program without functions, if we really had to do. But functions provide a number of great benefits.

First, they allow us to avoid repetition in our code. Many programs have instructions that are repeated: Asking a user to log in, reading data from a particular type of configuration file, or calculating the length of an MP3. While the computer won’t mind (or even complain) if the same code appears in multiple places, we — and the people who have to maintain the code after we’re done with it — will suffer, and likely complain. Such repetition is hard to remember and keep track of. Moreover, you’ll likely find that the code needs improvement and maintenance; if it occurs multiple times in your program, then you’ll need to find and fix it each of those times.

The term "don’t repeat yourself," often abbreviated as DRY, is a good thing to keep in mind when programming. And writing functions is a great way to apply the phrase, "DRY up your code."

6.1  XML generator

6.1.1  Solution

6.1.2  Discussion

6.1.3  Beyond the exercise

6.2  Prefix notation calculator

6.2.1  Solution

6.2.2  Discussion

6.2.3  Beyond the exercise

6.3  Password generator generator

6.3.1  Solution

6.3.2  Discussion

6.3.3  Beyond the exercise

6.4  Conclusion