Lesson 5: Creating Functions

Overview

In this lesson, students learn to define and call procedures (in JavaScript, procedures are called “functions”) in order to create and give a name to a group of commands for easy and repeated use in their code. They will be introduced to functions as a form of abstraction that enables them to write code in larger, more logical chunks and focus on what something does, rather than how it does it. As they explore the use of functions through a sequence of activities in App Lab, they will be asked to think about where they see the need for functions and how these functions can make their code clearer or more concise.

At the end of the lesson students review the concept of abstraction and are introduced to elements of the Create PT in preparation for the Practice PT at the end of the unit.

Purpose

Programming languages must necessarily define the meaning of a set of commands which are generally useful and applicable. In order to extend their functionality, nearly all programming languages provide a means for defining and calling new commands which programmers design to fit the needs of the problems they are trying to solve. Defining functions is an example of how computer scientists use abstraction to solve problems. A programmer will design a solution to a small, well-defined portion of the task and then give a name to the associated code. Whenever that problem arises again, the programmer can invoke the new function by name, without having to solve the problem again. This ability to refer to complex functionality by simple, meaningful names allows for programs to be written in more intuitive ways that reflect the relationships between different blocks of code.

Agenda

Getting Started (5 min)

Activity (35 min)

Wrap-up (15 min)

Assessment

Extended Learning

View on Code Studio

Objectives

Students will be able to:

  • Recognize functions in programs as a form of abstraction.
  • Write a program that solves a turtle drawing problem using multiple levels of abstraction (i.e. functions that call other functions within your code).
  • Explain why and how functions can make code easier to read and maintain.
  • Define and call simple functions that solve turtle drawing tasks.

Preparation

  • Review student-facing instructions in Code Studio

Links

Heads Up! Please make a copy of any documents you plan to share with students.

For the Students

Vocabulary

  • Abstraction - a simplified representation of something more complex. Abstractions allow you to hide details to help you manage complexity, focus on relevant concepts, and reason about problems at a higher level.
  • Function - A named bit of programming instructions.

Introduced Code

Teaching Guide

Getting Started (5 min)

Discussion Goal

Goal: Students have been solving turtle challenges with a limited set of commands. Recognize their desire to have access to more commands to solve these challenges. Motivate the fact they can create these new commands themselves, using the original turtle commands as building blocks.

Responses might include:

  • A command that turns the turtle to the right
  • A command that moves forward more than one space
  • A command that creates a repeated pattern or shape
  • Students may also just wish for different colors, curved lines, etc.

Discussion - The Need for Functions

Prompt: In the previous lesson we created simple turtle drawings using only four commands. At some point you probably wished that more commands were available to you. Describe a command you wanted to be able to use and explain why you wanted to use it.

Discuss: Provide students time to discuss their ideas with their neighbors before sharing with the class. This can be done fairly quickly but insist that students provide both the command they would have wanted and the situation in which they wanted to use it.

These will be addressed in a later lesson. Remind them they are thinking of commands to help with the last lesson’s challenge.

Remarks

Programming languages will always have some commands that are already defined, but there will be many instances when the exact command we want isn’t available. Today we’re going to start exploring a powerful feature of most programming languages that will allow us to overcome this issue and create commands of our own.

Activity (35 min)

Programming with Functions

Group: Place students in pairs. Consider using pair programming for this activity. If each student will work on their own computer have them check in with their partner throughout the activity.

Transition: Have students log in to Code.org

Wrap-up (15 min)

Create PT discussion goals

Goals:

  • Foreshadow the Practice PT at the end of the unit that has been designed to mimic most of the elements of the real AP Create PT
  • Students are aware of the major components they have to submit for the AP Create PT (1. annotated PDF of program code 2. wirtten responses 3. video)
  • Students understand that one of the key elements of the Create PT is identifying and responding to written prompts about an abstraction that they created to manage complexity.

Keep it short: Avoid making this a 45-minute deep-dive review of the AP Create PT and all its components - a surface level understanding is all that is needed to proceed. Practice questions and direct references to College Board materials are included in each of the next 5 lessons. This is a kickoff discussion, and you will have many opportunities to prepare students for the PT in later lessons.

Reflection on Abstraction Goals

Benefits of functions -- Possible responses:

  • programs are easier to read and write
  • functions remove the need to repeat large chunks of code
  • functions break the program into logical chunks
  • Functions are a way to give concise human-readable names to complex sections of code
  • Important to note: functions do not make the program easier (or harder) for the computer to run or understand -- it must still run all of the same commands as before.

Functions are examples of Abstraction -- Possible responses:

  • Abstractions simplify the representation of something more complex. A function gives a simple name to what might be a complex chunk of code.
  • Writing a function is a way to compartmentalize an idea
  • Abstraction helps manage complexity - so do functions because they let you break a problem into smaller parts.
  • Writing a function is a way to solve and then ignore lower-level, nitty-gritty problems in your program so you can focus on higher level problems.

Introduce Create PT (10 mins)

Distribute: Give students digital or printed copies of College Board - Assessment Overview and Performance Task Directions for Students. We will review pages 9-11 which introduces the Create PT Components (Digital copy linked to from student resource section for this lesson on code studio).

Remarks

At the end of this unit we will be doing a Practice Create PT that mimics most components of the AP Create PT. We're going to quickly review those components now, but we'll have opportunities to review and practice them in the next few lessons as well. For right now you don't need to understand all the details, just the big picture.

Review: Quick skim this document with the class, touching on the following points.

  • Page 9: The Create PT has 3 major components, 1. video, 2. written responses 3. program code. Students will skip the video this time as well as written response 2c.
  • Pages 10-11: Skim the submission requirements and give students time to read prompts 2a - 2d.
  • Highlight prompt 2d which references abstraction, the theme of this lesson and a focus of this unit.

Discuss: Respond to any questions students share. Don't lose too much time here. You'll have many opportunities to review the Create PT in later lessons.

Reflection on abstraction and managing complexity (5 mins)

Display the following questions somewhere they can be seen and ask students to write short responses before discussing with a neighbor. Once all pairs have had a chance to talk, bring the whole class back together to clarify points and share ideas.

Remarks

Let's start now making connections between writing functions and "developing abstractions" that help us when writing to programs

Prompt 1: List the benefits of being able to define and call functions in a program. Who specifically gets to enjoy those benefits?

Prompt 2: How is the use of a function an example of abstraction?

Assessment

Assessing Programs

If you wish, you may assess the final version of the diamond drawing that students develop in Code Studio. Suggested criteria are below.

  • The program draws the diamond.
  • The program defines four functions: right(), drawStep(), drawSide(), and drawDiamond(). The names are less important than the existence of four functions with this functionality.
  • The program makes a single call to drawDiamond().
  • The program looks clean and organized.

Questions

  1. Check the two items that are true statements about functions:
    • Meaningful function names help people better understand programs.
    • Meaningful function names help computers better understand programs.
    • Functions in programming are useful mathematical tools for doing complex computations.
    • Functions in programming are named groupings of programming instructions.
  2. In your own words explain at least one reason why programming languages have functions.

Extended Learning

Share and Compare

If students complete the diamond challenge early, ask them to compare their solution with another group. They should then try to create the version of the program that they believe is best with an associated justification. Challenge students to think about potential tradeoffs between efficiency and readability.

Keeping Going!

Groups that finish early can continue working with their functions to make more complex figures. Ask groups to continue building functions they think are generally useful for drawing.

View on Code Studio

Either as a class or individually, students should watch a video introducing the way that functions are defined and called in JavaScript. You may wish to take a minute following the video to address any questions that may have developed from watching the video.

  • Defining and Calling Functions
  • 2
  • (click tabs to see student view)
  • Using Functions With Turtle Commands
  • 3
  • 4
  • 5
  • (click tabs to see student view)
View on Code Studio

Student Instructions

Do This:

Define a function called turnAround which turns the turtle around. Once you've defined the function call it to make sure it works as you expect and then move the turtle forward, as shown below.

Remember typically, you call a function in lines of code above the function definition - this might make you feel like you are working in reverse, since you first write the code to define the function and then add a line to call it. Here is the moveTwice example from the video. You should do something similar for turnAround:

View on Code Studio

Teaching Tip

The exemplar programs have been written in the style that will be favored in this curriculum. These choices do not affect the functionality of a program but may affect the clarity with which a program can be read. In practice, so long as a consistent style is used, then programs will be easier to read and write.

camelCase: Function names are written in the camelCase. "Camel Case" refers to a stylized way of writing compound words or phrases. This means that multi-word function names are made a single word which begins in lowercase and uses uppercase letters to indicate the start of a new word. For example: camelCaseFunction()

Function Definitions at Bottom: Function definitions appear at the bottom of the program. This is done so that the first line of the program is the first line of code actually run. The opposite format is also very common.

Functions Names Can't Start with Numbers: In most programming languages, including JavaScript, function names are not allowed to begin with numbers or most symbols. Underscore, however, is allowed.

Student Instructions

Do This:

Get some more practice calling a function by using turnAround() along with your old friend the moveForward() function to create a plus sign that is centered at the turtle's first position, as shown below. Even though you just wrote this function, we've already defined turnAround() for you. Remember, add lines of code that call the function above the definition.

NOTE: the turtle should end where it started, which is also the middle of the plus sign, as shown below. Each of the four segments of the plus sign are one moveForward() long.

View on Code Studio

Student Instructions

Draw a rectangle with right

As you know, in order to turn right we have to call turnLeft() three times. We've started you out with a stub that defines a function called right(). Start by adding code inside the function definition that will turn the turtle to the right (by turning left three times) when called.

Then use this function in some code to draw a rectangle, as shown below. Make sure the turtle ends facing the same direction and in the same location it started. Note that the rectangle below is 2 moveForwards tall and 1 moveForward wide

Note: Your program will still do the same thing. We are just changing the way it is written to demonstrate that you can use functions you've already written as building blocks in new functions.

View on Code Studio

How to use this level

This level has a lot of text. Ways you might use it / incorporate it into your class:

  • Assign as reading for students the day before
  • Have students stop at this level during the normal progression and read as a group - discuss key points.
  • Read and summarize for your students
  • Make note of it as a reference for students that explains "abstraction"
  • Use in conjunction with a preview of the AP Create Performance Task
View on Code Studio

Abstraction - Managing Complexity

What is an abstraction?

Definition

An abstraction is a simplified representation of something more complex. Abstractions allow you to hide details to help you manage complexity, focus on relevant concepts, and reason about problems at a higher level.

Using abstractions in daily life

Modern life is filled with complex systems. Think for example, about a train system. It's theoretically possible to know the exact dimensions and turns of every rail on the system. If you just want to get from one place to another, however, these details are useless and even distracting. We need simpler representations of this complex system, like this map (source), to help us reason about and use it. In other words, we need an abstraction.

Abstractions and Computer Science



drawRectangle() and right() are examples of abstraction because they capture the code for more complex behavior and simplify the representation of that behavior by giving it a single name.

What it means in computer science

Computer science deals with complex systems too. Think about the incredible complexity of a system like the Internet. Humans just can't keep all those little details in their head!

In computer science we deal with complexity by "boxing it up" and giving it a name. For example, we develop a protocol to reliably send information from one person on the Internet to another. The protocol itself might be complex, but when we talk about it we can just call it "TCP". Simplified, high level representations of complex behavior make it possible to talk and reason about the complex systems we use and build in computer science. We call these representations Abstractions.

What it means in programming

Programs are complex systems. Individual commands may be easy to understand, but it can quickly become difficult to understand the logic and relationships connecting them. You need abstractions in your program code to let you "box up" these details so that you can focus on the bigger problem you're trying to solve.

Procedures (functions) are abstractions you make

Procedures (called "functions" in JavaScript) are abstractions you create. For example, by writing a function called drawRectangle(), you can "box up" and name the code necessary to draw a rectangle. Once you have tested that function and it works, you don't need to worry about the details of how it works anymore. You can now just use the simple, descriptive name you gave that complex underlying code (the name of your function). Creating abstractions like this helps you think about your code at a higher level, and makes sure you don't get lost in all the little details.

Abstraction, Unit 3, and the AP Exam

Abstractions help manage the complexity of the systems you build

As you'll see in this unit, the best way to build complex programs is to build abstractions. If you set out to build a complex turtle drawing (like the one to the right), you won't actually write all the individual movements and turns required to draw it. Instead you'll create abstractions (again, usually functions) that let you quickly express this complex behavior. This unit is largely about teaching you:

  • to use abstraction as a problem solving technique
  • to create and use abstractions in programs you write
  • to communicate about how abstraction helps you manage complexity

Abstraction and AP Computer Science Principles

(1) Abstraction is one of the seven big ideas of AP Computer Science Principles.

(2) For the AP Create Performance Task you need to...

[identify] a code segment that contains an abstraction you developed...[and]...explain how the abstraction helped manage the complexity of your program.


  • Using Functions With Turtle Commands
  • 7
  • 8
  • 9
  • (click tabs to see student view)
View on Code Studio

Student Instructions

This is your code from the previous level. Did you know that you can write functions that call your own functions?

Take the code that draws the rectangle and move into a new function called drawRectangle(). The first line of your program should be a single call to drawRectangle(). The rest of the code should just be function definitions.

NOTE: your program will still do the same thing. We are just changing the way it is written to demonstrate that you can use functions you've already written as building blocks in new functions.

View on Code Studio

Teaching Tip

MISCONCEPTION: Defining one function inside another

Be on the lookout for students trying to enclose one function definition within the other. When an instruction says something like: "Make sure to make a call to right() inside the drawStep() function" some students might try to place the definition for right() inside the definition of drawStep(), like so...

This code will not work because even though right is defined it is never called. There is another problem too -- while technically defining a function within another function definition is allowed in JavaScript it is odd and we will never have a construction like this in our course.

The intention is for each function definition to stand on its own. And for other code to call those functions. Here is the expected response (notice how right() is called from within drawStep).

Student Instructions

We are going to walk you through a process that shows you the benefit of thinking about programming tasks in terms of writing functions.

  • Over the next 3 levels we are going to write a program that draws the figure shown at right which sort of looks like a jagged diamond shape.

  • If you look at this image you might recognize elements that repeat: this is a 4-sided figure, and each side is made up of some zig-zag steps.

  • We're going to break the programming down into useable parts and then use those parts as building blocks to make this more complex drawing.

  • First let's define a function that draws just one of these zig-zag steps. We've started you out with a definition of right() that you can use...

Do This:

Define a function named function drawStep() which makes the turtle move forward and left as shown.

Note: at the end the turtle should be facing the same direction it started.

View on Code Studio

Student Instructions

Do This:

We are going to continue to build up towards a diamond by defining a function that draws one side of the diamond. If you look at the whole image we are trying to draw, you'll notice that each of 4 sides is comprised of 3 calls to drawStep(), plus a few extra moves (shown in orange).

Right now we'll write the code for one of those sides. So...

Define a new function named drawSide() which makes three calls in a row to drawStep() followed by a moveForward() and right().

Replace the original function call to drawStep() with a call to your newly defined drawSide() function.

The diagrams below show the intended actions.

![](https://images.code.org/480f6787e4d2daf34d67642e25b29de6-image-1441772552026.png) ![](https://images.code.org/02f52d406854d6f86535adf2f593ccc9-image-1441772709549.gif)
  • Challenge: Draw a Diamond Using Functions
  • 10
  • (click tabs to see student view)
View on Code Studio

Student Instructions

Do This:

We're finally ready to make our diamond! Define a function named function drawDiamond() that calls drawSide() multiple times in order to complete the drawing. Your final solution should be triggered by a single call to drawDiamond().


Notes:

In the end you will have 4 functions defined:

  • drawDiamond()
  • drawSide()
  • drawStep()
  • right()

These 4 functions work sort of like a hierarchy of top-down design. At the top is drawDiamond() which makes calls to drawSide(), which makes calls to drawStep() and right().

View on Code Studio

Teaching Tip

Correct answers:

  • Meaningful function names help people better understand programs.
    • Explanation: When a person is reading your program, it will be easier for them to understand what your program does (or is supposed to do) if your functions have clear and descriptive names.
  • Functions in programming are a named grouping of programming instructions.

Incorrect answers:

  • Meaningful function names help computers better understand programs.
    • Explanation: It doesn't matter to your computer what names your functions have, as long as you're consistent. Meaninful function names are strictly to make your code more understandable for humans.
  • Functions in programming are useful mathematical tools for doing complex computations.
    • Explanation: Functions don't necessarily have to do complex computations. Functions can be any set of actions you want the computer to perform.

Student Instructions

View on Code Studio

Teaching Tip

Correct answer:

  • Functions cannot make calls to other functions written by the same programmer.

Student Instructions

View on Code Studio

Student Instructions

In your own words, explain at least one reason why programming languages have functions. Include an example of something you did in this lesson that demonstrates the reason you describe.

View on Code Studio

Student Instructions


In this lesson we talked about how to build up solutions to larger programming problems with functions. Plan the code that you would use to draw this image (shown at right). Describe each of the functions that you would create. You should not write all the code, only the names of the functions that you would create with a brief description of what each function would do.

Write your plan following the format:

Name of function - description of what it does

Name of function 2 - description of what it does
...

Standards Alignment

View full course alignment

CSTA K-12 Computer Science Standards (2011)

CL - Collaboration
  • CL.L2:2 - Collaboratively design, develop, publish and present products (e.g., videos, podcasts, websites) using technology resources that demonstrate and communicate curriculum. concepts.
  • CL.L2:3 - Collaborate with peers, experts and others using collaborative practices such as pair programming, working in project teams and participating in-group active learning activities.
CPP - Computing Practice & Programming
  • CPP.L2:4 - Demonstrate an understanding of algorithms and their practical application.
  • CPP.L3A:3 - Use various debugging and testing methods to ensure program correctness (e.g., test cases, unit testing, white box, black box, integration testing)
  • CPP.L3A:4 - Apply analysis, design, and implementation techniques to solve problems (e.g., use one or more software lifecycle models).
CT - Computational Thinking
  • CT.L2:1 - Use the basic steps in algorithmic problem-solving to design solutions (e.g., problem statement and exploration, examination of sample instances, design, implementing a solution, testing and evaluation).
  • CT.L2:12 - Use abstraction to decompose a problem into sub problems.
  • CT.L2:3 - Define an algorithm as a sequence of instructions that can be processed by a computer.
  • CT.L3A:1 - Use predefined functions and parameters, classes and methods to divide a complex problem into simpler parts.

Computer Science Principles

2.2 - Multiple levels of abstraction are used to write programs or create other computational artifacts
2.2.1 - Develop an abstraction when writing a program or creating other computational artifacts. [P2]
  • 2.2.1A - The process of developing an abstraction involves removing detail and generalizing functionality.
  • 2.2.1B - An abstraction extracts common features from specific examples in order to generalize concepts.
2.2.2 - Use multiple levels of abstraction to write programs. [P3]
  • 2.2.2A - Software is developed using multiple levels of abstractions, such as constants, expressions, statements, procedures, and libraries.
  • 2.2.2B - Being aware of and using multiple levels of abstraction in developing programs helps to more effectively apply available resources and tools to solve problems.
5.3 - Programming is facilitated by appropriate abstractions.
5.3.1 - Use abstraction to manage complexity in programs. [P3]
  • 5.3.1A - Procedures are reusable programming abstractions.
  • 5.3.1B - A function is a named grouping of programming instructions.
  • 5.3.1C - Procedures reduce the complexity of writing and maintaining programs.
  • 5.3.1L - Using lists and procedures as abstractions in programming can result in programs that are easier to develop and maintain.
5.4 - Programs are developed, maintained, and used by people for different purposes.
5.4.1 - Evaluate the correctness of a program. [P4]
  • 5.4.1A - Program style can affect the determination of program correctness.
  • 5.4.1B - Duplicated code can make it harder to reason about a program.
  • 5.4.1C - Meaningful names for variables and procedures help people better understand programs.
  • 5.4.1D - Longer code blocks are harder to reason about than shorter code blocks in a program.

CSTA K-12 Computer Science Standards (2017)

AP - Algorithms & Programming
  • 3A-AP-17 - Decompose problems into smaller components through systematic analysis, using constructs such as procedures, modules, and/or objects.
  • 3B-AP-14 - Construct solutions to problems using student-created components, such as procedures, modules and/or objects.
CS - Computing Systems
  • 3A-CS-01 - Explain how abstractions hide the underlying implementation details of computing systems embedded in everyday objects.