7.3. Defining Functions - Why¶
We define functions for the same reasons we define procedures:
To reuse code without having to type it multiple times or copy/paste it
To make abstractions that allow us to focus on the big picture while solving a problem. These abstractions also make it easier for others to get some bit of work done without worrying about the details of how it works.
Our program on the last page to calculate the length of side c of a triangle did not really benefit from making use of a function. We only did the calculation one time and the work we were doing in the main part of the program was not all that complex. We could have just calculated the length of the missing side by doing all the calculations in the main part of the program.
Here is a program that shows off why a function can be useful. I am trying to use 20 feet of material to make two sides of a right triangle. I want the length of the long side to be as close to 15 feet as I can make it. So I decide to calculate the length of the hypotenuse for different triangles - one where I make both legs 10; one where I make the legs 11 and 9; one where I make the legs 12 and 8; etc… Looking at the results of these calculations, I can see that my best option is to use lengths of 14 and 6 (which produces a hypotenuse just a bit closer to 15 than sides of 13 and 7).
Now look below at a version of this program without a function.
Not only did writing it involve retyping lines like aSquared = math.pow(___, ___)
over and over, and it is harder to read and understand.
A function call like hypotenuse_length(15, 5)
allows us to instantly see
“Oh, that is just where we are going to calcualte the hypotenuse.”. When there is no function,
the reader has to slog through things like this:
aSquared = math.pow(10, 2)
bSquared = math.pow(10, 2)
hypotenuse1 = math.sqrt(aSquared + bSquared)
As they do so, they must come to their own conclusion “Oh, I think I see what is going on, we are doing all the math to calculate a hypotenuse”. Doing this distracts them from the big picture of the problem we are really trying to solve.
Check Your Understanding