Sunday 7 December 2008

Functions First Draft


Functions are extremely useful structures, that allow us to use the same code in various places, by calling a function's signature. The signature of a function is its first line. If we have a function with the signature:
void drawCircles(int a)
then we call it like so:
drawCircles(400);
If there is a function with the same name but a different signature it is known as an overloaded function:
drawCircles(int a, String col)
we could call the second overloaded function like so:
drawCircles(400, "red");
Code that is repeated frequently is an indication that a function is required. The repetitive portion of the code should be moved into a function with any parameters required. This helps with code reuse, making the program easier to maintain and cuts down the program's length. Any errors/modifications are confined to one place and can be easily corrected.
There are three basic types of functions:
A simple function is usually used to change some global variable's value. It doesn't accept any parameters and returns no value. The changeColour() function line 105 provides us with an example. It has a void return type and empty parameter brackets.
Some functions can be passed messages, informing them of value/s to change or use. drawCircles3(int) on line 118 accepts an integer which it uses to draw a circle, using the ellipses method.
A function can be used to perform some calculation and return a value. These type of functions must contain the return type in their signature. The getSW function on line 135 returns an int value, which can be used to set the stroke width. The signature has type int to denote its return type:
int getSW()
A function can also accept parameters and return a value. We havent used this type of user defined function in chunk 16.
As well as allowing us to create user defined functions, Processing has its own inbuilt functions, which is probably the main reason for using it.
Some builtin Processing functions are:
The size function, accepts two integers, which set the size of the display window in the setup method.
The rect(int, int, int, int) function, accepts four parameters, that are used to draw a rectangle. The first two parameters are the coordinates for the rectangle's position and the remaining values, set the rectangles width and height.
The random function is an overloaded function, because it can accept either one or two parameters. It can return a float or an integer. In chunk 16 we mostly use integers, so we need to round up any floats returned by random. We pass the value returned by the random(int, int) function into the round(float) function to obtain an integer. Examples of using round(random(int, int)) can be found in many places in Chunk16 as it outputs randomized patterns. Some examples of values that are randomised using the random function are: stroke width, colour, height. width, interval and patternsPerPicture.

No comments:

Post a Comment