Designing reusable code:
Functions
DECO1012 - Design Programming
Week 4
Recap: Generative design
● Generative design
● Random function
● Noise function
● Easing
● Sin & Cos
● Timing (millis() & frameCount)
Slide 2
let xPos = random(width);
let redAmount = random(100, 255);
fill(redAmount, 100, 100);
circle(xPos, height/2, 100);
Reusable code
Reusable code
To reduce the chances for us to introduce bugs in our code, we want to avoid
writing code as much as possible. One way we can do this is to design reusable
code.
Another reason to design reusable code is that it is easier to modify, we only need
to change things once, in one place, to have an effect all over our programs.
A final reason to design reusable code is that it makes it easier to share snippets
of code for others to use.
Slide 4
Reusable code
The most basic example of designing
with reusable code is the inclusion of
variables:
Slide 5
let circSize = 100;
circle(width*0.25, height/2, circSize);
circle(width*0.50, height/2, circSize);
circle(width*0.75, height/2, circSize);
If we want to change the
size of our circles, we only
have to change this one
line. This makes it easier to
modify the look of our
design as well as reduces
opportunities to introduce
bugs.
Reusable code
Another way we already know how to
reduce repeated code is with loops:
Slide 6
let circSize = 100;
for(let x = 0.25; x < 1; x+=0.25){
circle(width*x, height/2, circSize);
}
Custom functions
Custom functions
Another way we can create reusable code is via custom functions.
We’re already worked with functions a lot such as ellipse, background,
and fill. These are all functions provided to us by p5.
We also have worked with some function definitions: draw and setup.
These are examples of functions which we define and are called for us
by p5.
We can create our own custom function definitions and then call them
ourselves.
Slide 8
Custom functions: syntax
The syntax for creating a custom function is something we have already seen from
setup and draw:
function myFunctionName(){
//code to run when function called
}
Slide 9
Custom functions: syntax
We also know that some functions, like fill, take in parameters. We can use
parameters within our functions like this:
function circleInMiddle(circSize, circColor){
fill(circColor);
circle(width/2, height/2, circSize);
}
Slide 10
Inside the function we can use our
parameters like they are variables
defined with let
Custom functions: syntax
Some functions, like random, also return a value to us:
let randNumber = random(100);
Slide 11
We can create our own custom function that returns a value using the return
keyword:
function getXPointOnCircle(angle, radius){
let xPos = sin(angle) * radius;
return xPos;
}
Return also ends the function call
immediately, so any code after this return
keyword would never run.
Custom functions:
complete example
Imagine I want to draw a stripy
background:
This is fine, but my draw loop is
getting messy: we only get one
draw loop.
Slide 12
let numAcross = 10;
let colorA, colorB;
function setup() {
createCanvas(400, 400);
colorA = color("#fac2be");
colorB = color("#f2dcda");
}
function draw() {
for(let x = 0; x < numAcross; x++){
let xPos = map(x, 0, numAcross, 0, width);
if(x % 2 == 0){
fill(colorA);
} else {
fill(colorB);
}
rect(xPos, 0, width/numAcross, height)
}
}
Custom functions:
complete example
Now let’s refactor this code with
a function:
I can now easily drop this
function into my draw loop,
making it nice and neat
Slide 13
function stripyBG(nAcross, colA, colB){
for(let x = 0; x < nAcross; x++){
let xPos = map(x, 0, nAcross, 0, width);
if(x % 2 == 0){
fill(colA);
} else {
fill(colB);
}
rect(xPos, 0, width/nAcross, height)
}
}
Custom functions:
complete example
Our draw loop is now much
clearer, and we now have a
handy stripyBG function we can
drop into any project and use.
Slide 14
let numAcross = 10;
let colorA, colorB;
function setup() {
createCanvas(400, 400);
colorA = color("#fac2be");
colorB = color("#f2dcda");
}
function draw() {
stripyBG(numAcross, colorA, colorB);
}
function stripyBG(){
...
We put out our function definitions
down here, outside of draw and
setup.
Also note that we we’re able to use
the stripyBG function before we
defined it. That’s because
javascript is a hoisted language.
Custom functions:
A reusable example
That last example wasn’t being
reused within the program, let's
look at an example where we
do!
Slide 15
function setup() {
createCanvas(400, 400);
centeredCircle(0.25);
centeredCircle(0.50);
centeredCircle(0.75);
}
function centeredCircle(xPosPercent){
fill('skyblue')
circle(xPosPercent*width, height/2, 100)
}
Challenge 1: The Target Function (15 minutes)
You now have everything you need to attempt the first challenge on canvas.
Remember to consult the p5 reference pages.
Code folding: Many editors, including the p5 editor, allow you to fold up your code. This lets you reduce
‘cognitive load’. Once you understand how the target function works, you can fold it away:
Make sure to ask for help if you need it.
Slide 16
This arrow lets you fold up any block of code
Custom shapes
Custom shapes
Before we continue using functions, let’s quickly go over how to make a custom
shape.
To make a custom shape, we must first call the beginShape() function. Then, we
specify a number of vertex positions to make up our shape. Finally we call the
endShape() function to finish our shape.
Depending on what parameter we pass into the beginShape and endShape
functions, we will get slightly different results. In most cases, beginShape with no
parameters and endShape(CLOSE) will be the correct setting.
Slide 18
Custom shapes
In this example, we create a
triangle using custom shapes.
This is a trivial example
because the triangle() function
already exists.
Slide 19
beginShape();
vertex(width/2 - 100, height/2);
vertex(width/2 + 100, height/2);
vertex(width/2, height/2 + 100);
endShape(CLOSE);
Even though this isn’t a code block,
some people like to indent here to
make it extra clear.
Custom shapes
In this example, I have made a function which
draws a polygon with any number of sides:
Slide 20
function polygon(numSides, radius){
beginShape();
for(let angle = 0; angle < TWO_PI; angle += TWO_PI/numSides){
let xPos = sin(angle) * radius + width/2;
let yPos = cos(angle) * radius + height/2;
vertex(xPos, yPos)
}
endShape(CLOSE);
}
Challenge 2: Applying the weirdShape Function (15 minutes)
You now have everything you need to attempt the second challenge on canvas.
Remember to consult the p5 reference pages.
Make sure to ask for help if you need it.
Slide 21
Refactoring
Refactoring
Refactoring is when we simplify, neaten, parameterize, abstract, and otherwise
improve our code, without changing its functionality.
When we restructure our code in this way, we make it easier to understand, more
shareable, quicker to modify, and sometimes even faster (changing the code for
the explicit purpose of making it faster is called optimisation).
Slide 23
Refactoring
Examples of refactoring include:
● Changing variable names to be more descriptive
● Moving code out of setup and draw, into its own function
● Parameterizing hard-coded values
● Removing redundant code
● Using loops and functions to reduce repeated code
Slide 24
Challenge 3: Refactor with Functions (15 minutes)
You now have everything you need to attempt the third challenge on canvas.
Remember to consult the p5 reference pages.
Make sure to ask for help if you need it.
Slide 25
Extension Challenge: Creating a Suprematist Composition
As an additional extension this week, we recommend you try out the final challenge,
creating a suprematist composition.
Remember to consult the p5 reference pages.
Make sure to ask for help if you need it.
Slide 26
Before we wrap up…
Try and re-try this week’s challenges before the next class. Practice helps!
Assessment 1: Part C quiz will be released on Mar 18 at 13:00. Complete this quiz by Mar
24 at 23:59.
Questions? Post your coding questions on the Slack channel.
If you need to talk to your tutor, arrange for a meeting using Canvas (option to setup a
meeting available in the Home page).
Slide 27
See you next week!
Design Programming - Week 4 Tutorial