CP- User Defined Functions Lesson
User Defined Functions
So far we've been using predefined functions that are in the processing library. However, writing your own functions is very important. You might have hundreds of lines of code if you didn't create user defined functions. A User Defined Function is a function that the user creates for a specific purpose.
Writing your own functions is important for two reasons:
- Modularity: It breaks the code into manageable pieces so it is easier to read and revise.
- Reusability: You can reuse the function over and over again without having to retype it.
Refer back in this module to recall the syntax for creating a function. You learned the format for creating a function by using setup() and draw().
There are two types of functions:
- return functions
- void functions
User Defined Functions Video
Watch the User Defined Functions video below.
Creating Return Functions
A return function returns a value. Remember random() is a return function because it returns a number.
A return function specifies the type of data it is returning as the return type. All return functions must have a return statement.
You can print the information from a return function using the println() or print() function. You can also use a return function to assign data to variables.
You can use the getMouseX() and getMouseY() function created above as the arguments passed to the parameter in the line function below.
line(150, 25, getMouseX(), getMouseY());
Creating void Functions
Void functions perform an action.
This function would assign the variable x to 10.
Overloaded Functions
Overloaded functions pass arguments through the parameter that assign the data to local variables inside the method.
When this method is called a value is passed through the parameter that will be assigned to factor. This will be used to multiply the current value of x times speed and add it to x.
Calling Functions
setup() and draw() are functions that are automatically called by processing when a sketch is run. Functions are typically written below the draw() function and are called inside setup() and draw().
[CC BY 4.0] UNLESS OTHERWISE NOTED | IMAGES: LICENSED AND USED ACCORDING TO TERMS OF SUBSCRIPTION