Lesson 19: Functions

Overview

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.

Purpose

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.

Assessment Opportunities

  1. Create and use functions for blocks of code that perform a single high-level task within a program

    See Level 12 in Code Studio.

  2. Explain the advantages of using functions in a program.

    In the wrap up discussion, make sure students understand that functions can increase both the readability and organization of code.

  3. Explain how abstractions allow programmers to reason about a program at a higher level

    In the wrap up, students should make the connection between functions and abstraction, that functions allow a programmer to name a bit of code so that they can think about it at that higher level, rather than worry about all the details.

Agenda

Warm Up (10 mins)

Activity (60 mins)

Wrap Up (10 mins)

View on Code Studio

Objectives

Students will be able to:

  • Create and use functions for blocks of code that perform a single high-level task within a program
  • Explain the advantages of using functions in a program.
  • Explain how abstractions allow programmers to reason about a program at a higher level

Vocabulary

  • Function - A named bit of programming instructions.

Introduced Code

Teaching Guide

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.

Discussion Goal

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.

Content Corner

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.

Remarks

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)

Assessment Opportunity

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.

Assessment Opportunity

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.

Remarks

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.

View on Code Studio

Discussion Goals

Make sure students understand role of the two steps in using functions, as well as seeing functions as a form of "chunking" or abstraction. The function definition should include all of the code that they want to run, and the name of the function should be a short description of the purpose of the code. The function should be called at each place in the program that the student wants that block of code to run.

View on Code Studio

Questions to Consider

  • Think of a time when a function might have helped you write a program.
  • What code would go in the definition of the function?
  • When would you call the function?
  • What would you name it?
View on Code Studio

Teaching Tip

Introducing Functions

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.

Student Instructions

Calling Functions

Functions let you build your own blocks and decide what code goes inside of them. This program has already created two functions, but only one of them is being called.

Do This

  • 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.
View on Code Studio

Student Instructions

Reordering Code

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.

Do This

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
View on Code Studio

Student Instructions

Does It Matter Where You Create Functions?

So far all your functions have been created at the bottom of your code. What do you think will happen if you call a function before it's defined?

Notice that the red square is drawn before its function is created while the green square is drawn after its function is created. Which of these do you think will be drawn?

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.

View on Code Studio

Student Instructions

Calling Functions in the Draw Loop

You can call a function inside the draw loop, just as you would anywhere else in your code.

Do This

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.
View on Code Studio

Teaching Tip

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.

Student Instructions

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.

Do This

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.
View on Code Studio

Student Instructions

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.

Do This

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.

View on Code Studio

Student Instructions

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.

Do This

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 drawNight function 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 drawDay function to help you at all?
View on Code Studio

Teaching Tip

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.

Student Instructions

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.

Do This

  • Read and run the code that already exists to make sure you know how it works.
  • Write the code for the setCoin function to make the coin fall from the sky.
  • You can go look at some of the previous levels if you need help.
View on Code Studio

Student Instructions

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.

Do This

  • 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.
View on Code Studio

Assessment Opportunities

Key Concepts:

Define and call functions to organize code and make it easier to reuse.

Assessment Criteria:
Extensive Evidence

The two functions are defined and called within the if statement as instructed, so that different backgrounds display according to the current score. Code is correctly organized inside and outside the draw loop, and there are no extra blocks.

Convincing Evidence

At least one new background function is defined and called successfully inside the program, but may not work exactly as instructed. Code is correctly organized inside and outside the draw loop.

Limited Evidence

A function is both defined and called inside the program, but there may be major errors that prevent it from running successfully, or code has been incorrectly placed in the draw loop.

No Evidence

There are no new functions in the program.

Student Instructions

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.

Do This

  • 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!
  • Levels
  • Extra
  • (click tabs to see student view)
View on Code Studio

Student Instructions

Free Play

Use what you've learned to create whatever you like. When you're finished, you can click to send your creation to a friend, or to send it to your Projects Gallery.

Standards Alignment

View full course alignment

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.