Hi Everyone!
Dr. Guthals here, and this week I wanted to do a quick review on functions.
Functions are very tricky. I TA’d for undergraduate computer science majors at UCSD, and that was one of the hardest concepts to learn in the first couple courses. In LearnToMod, we try to make them a bit easier by using a block-based language, but they are still strange and sometimes confusing.
In this post, I’m going to give you a few ways that I like to explain functions, and hopefully one (or a combination) of these will help you and your students understand them a bit better.
The Wiggle Dance
I particularly like this one with younger students, but it works as a good example for all ages (I even use it when I train educators). Imagine I had a choreographed dance that consisted of a combination of three moves. My three moves are:
Hand Wiggle
- Wiggle Right Hand
- Wiggle Left Hand
- Wiggle Both Hands
Foot Wiggle
- Wiggle Left Foot
- Wiggle Both Feet
- Wiggle Right Foot
Body Wiggle
- Wiggle Head
- Wiggle Hips
- Wiggle Head
Now, the Wiggle Dance is a combination of Hand Wiggles, Foot Wiggles, and Body Wiggles, it might go like this:
- Hand Wiggle
- Foot Wiggle
- Body Wiggle
- Foot Wiggle
- Hand Wiggle
And it’s already hard to remember 5 steps, but imagine if I didn’t name them Hand, Foot, and Body Wiggle, then the steps would look like this:
- Wiggle Right Hand
- Wiggle Left Hand
- Wiggle Both Hands
- Wiggle Left Foot
- Wiggle Both Feet
- Wiggle Right Foot
- Wiggle Head
- Wiggle Hips
- Wiggle Head
- Wiggle Left Foot
- Wiggle Both Feet
- Wiggle Right Foot
- Wiggle Right Hand
- Wiggle Left Hand
- Wiggle Both Hands
And remembering 15 steps is way harder! It also makes it harder to change the steps to be a different order. This is just like the functions, it is a name that you give to a set of steps, just like the wiggle dance steps.
Using Code
You can explain it in the same way, but with code, by showing a snippet like this:
Main is where Minecraft always starts. From there – it does everything in order, so if we were to not use functions, our code would look like this:
In this case, it might not seem like that big of a difference, but imagine that each of the functions had 20 lines of code in it. Or imagine you wanted to add one more UpAndRight in the middle. Having everything all in one function makes it harder to debug and makes it harder to read (as humans). The computer doesn’t really care – it will run the code however you write it, but it will make it harder for you. Now, you can make sure your UpAndRight function works properly, and make sure your DownAndLeft function works properly, and then only focus on main for the overall pattern!
I hope this has helped with a basic explanation of functions. Do you have another way of explaining them? Share with us by emailing educators@thoughtstem.com and/or joining our online Meetup (here) and posting it there!
Happy Modding!