Vera Molnar. PAGE 38. May 1977.
Functions Returning Values
In the last chapter, we created a function to draw a new geometrical form - a cross. However, this is only half the story because we can also define functions that return values. Indeed we often make the distinction by saying that a function either returns a value or it doesn't. In the latter case, as in our cross, the function returns void. Hence, the keyword void still used today in Java & Processing.
To demonstrate this concept of returning a value, we are going to define a function that will animate our cross. Now, we could quite simply make our cross move by passing in a variable and making that change over time. That may be fine for a few isolated cases within a program but once we start repeating ourselves, it may be time to make a function.
Again, our thinking here is to make our code clear, readable and reusable too. Writing a function encapsulates a specific idea that we can easily identify, understand, implement and reuse throughout our program and indeed in other programs. So, whenever you find yourself repeating certain commands or proceedures in your program, it's time to combine these instructions within the structure of a function.
You'll notice that the syntax is basically the same as our cross function example. However, there are two major differences. The first is the use of the keyword, return used at the end of the body of our function. All functions of this type return a value from within the function. If you look carefully at the body, you'll see that this value is in fact a variable. We are declaring a variable, assigning it a value, doing some operations on that data then finally returning the result.
To use our function, we simply call it where we need it. Our function is returning a value, so we'll want to first store that value in a variable. We could of course call this function within another function, directly as an argument to that function. This style of programming is quite common but it lacks readability and it is it much clearer to declare a new variable and assign the function to it. This can then be used as a argument for multiple functions.
Eg 2. java // declare variable & assign it our function float crossSize = oscillate();
.../* we then pass this variable as a parameter to our cross function, modifying the size of our cross */ fill(0,0,255); cross(width/2, height/2, crossSize); ...
We could easily add parameters to our function in order to control the frequency and amplitude for our harmonic oscillation. This would enable us to animate some form with varying motion. We could also use the function to animate our cross's position as in the example below. You'll use functions all the time. Infact you already did without knowing it ;—) Now you know how to make your own.