Lesson 19: Functions
Students learn how to create functions to organize their code, make it more readable, and remove repeated blocks of code. An unplugged warmup explores how directions at different levels of detail can be useful depending on context. Students learn that higher level or more abstract steps make it easier to understand and reason about steps. Afterwards students learn to create functions in Game Lab. They will use functions to remove long blocks of code from their draw loop and to replace repeated pieces of code with a single function. At the end of the lesson students use these skills to organize and add functionality to the final version of their side scroller game.
In the first four lessons of this chapter students have learned to use a number of abstractions in their programs, including the velocity properties, isTouching, and collisions. These abstractions have allowed them to build much more complex programs while ignoring the details of how that behavior is created. In this lesson students learn to build abstractions of their own by creating functions.
Students will primarily use functions to break code into logical chunks that are easier to reason about. This foreshadows the chapter's transition from building technical skill to the organizational processes used to develop software.
Warm Up (10 mins)
Activity (60 mins)
Wrap Up (10 mins)
Students will be able to:
- Create and use functions for blocks of code that perform a single high-level task within a program
- Create and use functions to remove repeated blocks of code from their programs
- Create and use functions to improve the readability of their programs
- Explain how abstractions allow programmers to reason about a program at a higher level
- Function - A named group of programming instructions. Functions are reusable abstractions that reduce the complexity of writing and maintaining programs.
Warm Up (10 mins)
High Level vs. Low Level Instructions
Prompt: Imagine you needed to write a 5-step set of instructions for going through your morning. What would they be? Write down your steps and be ready to share.
Goal: This conversations demonstrates to students that they often use a high level name or description for much more complex behavior. It is motivating the value of grouping or combining lots of smaller steps under a larger name and provides some of the justifications for creating functions within programs. Namely, high level steps make it easier to understand and reason about a process.
Breaking Down Processes: The order in which they are breaking down a larger task here also mirrors how they'll be asked to write code with functions. Often programmers first write the name of the function they intend to write based on what it should do before actually going in and writing the details.
Discuss: Student should write 5-step instructions for their morning and share with a neighbor. Ask a couple of students to share with the class.
Prompt: This set of instructions is pretty easy to follow and understand. They're at the level you might think about when describing your day to a friend. Now let's go a level deeper. Pick one of your 5 steps and split it into 5 smaller steps you need to complete that larger task. Be ready to share your ideas again.
Discuss: Students should share their smaller steps. Again ask some volunteers to subsequently share their original step and how they split it up.
Discuss: This is getting interesting. It seems like the first time we gave our steps we were "hiding" some of the details necessary to complete the task. Let's try this once more. Take one of your 5 smaller steps and split it up again into 5 even smaller steps.
Discuss: Ask students to share their steps one more time. Again ask some volunteers to share how they broke up one of their steps into even smaller steps.
Prompt: Imagine we had split every one of your first 5 steps into 5, and then split all of those steps again. This would mean we would have a high level set of instructions, and at the bottom a really low-level or detailed set of instructions. Be ready to respond to the following questions.
- When would the high level set of steps you just wrote be most appropriate?
- When would the lowest level set of steps be most appropriate?
- Which one is easiest to reason about or understand?
Discuss: Ask students to share their thoughts and opinions. After a couple of minutes move the conversational to the transitional comment below.
Sometimes details are important, but often high level steps are much easier to reason about and make it clear what's happening. In programs the same thing is true. We've learned that blocks like velocityX or isTouching actually just contain code that we could've written ourselves. Using these commands, or abstractions, is really helpful since we can think about code at a high level. Today we're going to learn how to group lots of commands to create a single new block our own. In programming when we create a new block like this we call it a function.
Activity (60 mins)
Transition: Move students into Code Studio where they will learn to create an call functions.
Wrap Up (10 mins)
Goal: Use this first prompt to review what students learned today. When they create a function they are creating their own block that they can call or use whenever they like. They saw at least two primary motivations for creating functions today including.
- Simplifying code by breaking it into logically named chunks
- Avoiding repeated code by making one block you can use multiple times.
Prompt: Why would we say that functions allow us to "create our own blocks?" Why is this something we'd want to do?
Discuss: Have students discuss at their table before talking as a class.
Goal: Students should review the definition of abstraction as "a simple way of representing something complex". Note that a function is an abstraction because it allows you to create one simple name for a more complex block of code.
Prompt: Write down your own definition of an abstraction? Why would a function count as an abstraction?
Discuss: Have students discuss at their table before talking as a class.
Functions are a useful tool for helping us write and organize more complex pieces of code. As we start looking to end of the unit and your final project, being able to keep your code organized will be an important skills.
In these first several lessons students are just being shown the syntax of functions and are not asked to write or create their own. It can be useful to explain creating a function as basically “creating a new block” just like another programmer created the “isTouching” or “velocity” blocks that they’ve seen actually contain other more complex code.
Functions let you build your own blocks and decide what code goes inside of them. This is the command that lets you create a new function.
You use or "call" your function like any other block by using the name you gave it.
The blocks to create and call functions can be found in the "Functions" tab of the palette.
This program has already created 2 functions. Only one of them is being called.
- Call the second function to reveal the full image. Use the function that is being called as a guide.
- Tip: Just as with all other blocks, spelling and capitalization are important here.
Placing code inside functions makes it easy to read and make changes to. Good names for functions indicate what your program is doing to a reader. You can call your functions in a different order to quickly make significant changes to how your program runs.
This program has already created 4 functions that draw parts of a scene. Unfortunately it's not coming out right.
- Read the 4 functions to know what they do
- Call the functions in an order that draws the scene in the way that looks best to you
The red square will be drawn but the green one will not. You cannot call functions after they are created.
The green square will be drawn but the red one will not You cannot call functions before they are created.
Both squares will be drawn. You can create functions anywhere you like in your code.
Neither square will be drawn. There is an error in the code.
Calling Functions in the Draw Loop
You can call a function inside the draw loop, just as you would anywhere else in your code.
A function that will draw a background has been created for you. A sprite has been created to move across the background.
- Call the function inside the draw loop so that the sprite appears on top of the background.
- Note: Don't create functions inside the draw loop. Make them at the bottom of your code.
Why Use Functions
This and the next two levels introduce three uses of functions, namely removing repetition in programs, allowing code to quickly be changed at multiple points, and providing organization in code. Students will need to write more of their own functions in these levels.
Calling Functions Multiple Times
You'll often want to use the same code at many places in your program. Once you've created a function you can call it as many times as you like.
This code creates a sprite that moves across the screen once. How can you make it go back across the screen?
- Note: The function is already called once at the beginning of your program
- Read the condition of the if-statement inside the draw loop. Why do you think it's there?
- Use this if-statement and the function written for you to make the sprite move across the screen multiple times.
Making Changes to Functions
A nice benefit of using functions to remove repeated code is that you can now easily make changes to multiple places in your code. Just change how you create the functions, and your program will now use the new code everywhere your function is called.
Make changes to the
setFlyer function so that the flyer starts at a random Y location between 0 and 400, and moves at a random velocity every time he is reset.
Creating Functions to Organize Code
In Game Lab all the action is happening in the draw loop, but too much complex code makes it really confusing to read. To keep your draw loop easy to read, use functions for larger chunks of code. You can call them inside the draw loop and define them below. This is a really good example of using abstraction to think about problems at a high level and worry about details later.
This program should draw a daytime scene or a nighttime scene, depending on the location of the mouse. The draw loop describes what needs to happen but one of the functions hasn't been written yet.
- Write the
drawNightfunction which has been created but is empty.
- Hint: Look at the picture to the right for how your night image should look. Can you use the
drawDayfunction to help you at all?
Functions in Context
In this and the next two lessons, students will use functions to organize code within a simple game. While it is not identical to the side scroller, many of the skills and uses of functions in these levels can and should be used when they complete their side scroller.
Write Your Own Function
Time to practice writing functions of your own. This is a very simple game in which coins fall from the sky and the bunny tries to catch them. All you need to do is write the function that sets up the coin.
- Read and run the code that already exists to make sure you know how it works.
- Write the code for the
setCoinfunction to make the coin fall from the sky.
- You can go look at some of the previous levels if you need help.
Catch the Coin, Increase the Score
Let's make that score change now, too, to complete the game. You'll need to be able to tell when the bunny is touching the coin and then reset it.
- Use an if-statement and the isTouching block to increase the score when the bunny catches the coin.
- Make sure you're calling your function to reset the coin once it's been caught.
- Play the game and randomize the velocity of the coin to a range that you think is fun.
Change the Background with the Score
Once you've caught 10 coins it's time to celebrate. You should change the background to be something fun.
- Use an if-statement and two separate functions to draw your backgrounds.
- Then go write your functions outside your draw loop. You get to decide what a "simple" or "crazy" background are. Have fun with it!
CSTA K-12 Computer Science Standards (2017)
AP - Algorithms & Programming
- 2-AP-11 - Create clearly named variables that represent different data types and perform operations on their values.
- 2-AP-12 - Design and iteratively develop programs that combine control structures, including nested loops and compound conditionals.
- 2-AP-13 - Decompose problems and subproblems into parts to facilitate the design, implementation, and review of programs.
- 2-AP-14 - Create procedures with parameters to organize code and make it easier to reuse.
- 2-AP-16 - Incorporate existing code, media, and libraries into original programs, and give attribution.
- 2-AP-17 - Systematically test and refine programs using a range of test cases.
- 2-AP-19 - Document programs in order to make them easier to follow, test, and debug.