Review: Fruitless functions (for effect)

Here's a couple of lines that draw a shape (a circle and a square).

function setup() {
	createCanvas(windowWidth, windowHeight);
	background(100);
}

function draw() {
	circle(mouseX, mouseY, 20);
	square(mouseX, mouseY, 30);
	
}

Extract them into a function.

function draw() {
	squareAndCircle();
}

function squareAndCircle() {
	circle(mouseX, mouseY, 20);
	square(mouseX, mouseY, 30);
}

Parameterize the function.

function draw() {
	squareAndCircle(mouseX, mouseY);

}

function squareAndCircle(x, y) {
	circle(x, y, 20);
	square(x, y, 30);
}

Use return to exit the function early

This function only sometimes draws the shape.

These are two different ways of doing the same thing.

function squareAndCircle(x, y) {
	if (x < 300) return;
	circle(x, y, 20);
	square(x, y, 30);
}
function squareAndCircle(x, y) {
	if (x >= 300) {
		circle(x, y, 20);
		square(x, y, 30);
	}
}

Fruitful Functions

squareAndCircle(), above, is called for effect. Calling it has an effect on something (in this case, on what's in the canvas). circle() and square() are p5 functions that are also used for effect.

sin(), in contrast, is called in order to use its value. The call to sin() in this code doesn't do anything (except slow the program down slightly):

function draw() {
	sin(10);
}

In order to use make use of sin(), we need to do something with the value that it returns.

function draw() {
	let d = sin(10);
	circle(d, d, 10);
}

A sequence of statements that are executed for effect can be extracted into a fruitless function, that is called for effect. This is what we did with circleAndSquare(), above.

An expression can be extracted into a fruitful function, that uses return to send a value back to the code that calls it. The following two codes have the same effect.