programmingconcepts

§ 1.3 · Foundations

Functions

A named, reusable block of code that takes inputs, does one job, and gives back a result.

A function is a named block of code that does one job. You pass it inputs, called arguments, it runs, and it can return a result. Functions let you reuse code, name a piece of logic, and test it on its own. Each call gets its own local variables, kept on the call stack.

Takes
Parameters (inputs)
Gives back
A return value
Each call gets
Its own local variables
Kept on
The call stack
Requires
Control flow

Why functions

Without functions, you’d copy the same lines everywhere you need them, and fix every copy when there’s a bug. A function lets you write the code once, give it a name, and call it from anywhere. The name also documents intent: spread(scores) says more than six lines of loop.

Anatomy

def spread(values):       # name and parameters
    low, high = min_max(values)
    return high - low     # the result

gap = spread([3, 9, -2])  # a call, with an argument
  • Parameters are the names in the definition: values.
  • Arguments are the actual values passed in a call: [3, 9, -2].
  • return ends the function and hands a value back to the caller. A function without one returns nothing: None in Python, undefined in JavaScript.

Returning more than one thing

The example finds the smallest and largest value in a list, which is two results. Each language has its own way to return both, and its own way to say “there were no values”:

def min_max(values):
    """Return the smallest and largest value, as a pair."""
    if not values:
        raise ValueError("min_max() needs at least one value")
    smallest = largest = values[0]
    for v in values[1:]:
        if v < smallest:
            smallest = v
        if v > largest:
            largest = v
    return smallest, largest


def spread(values):
    low, high = min_max(values)  # call it, then unpack the two results
    return high - low
  • Python returns a tuple and unpacks it with low, high = .... An empty list raises an error.
  • JavaScript returns an array and destructures it with const [low, high] = ....
  • Go has real multiple return values, plus an ok flag for the empty case.
  • Rust returns Option<(i32, i32)>: either a pair or None, and ? passes None straight on.

Scope and the call stack

Variables created inside a function are local. They exist only during that call, and other functions can’t see them. Two calls to the same function each get their own copies.

That works because every call gets a fresh stack frame on the call stack, holding its parameters and locals. When the function returns, its frame is removed. A function that calls itself is recursion, and the stack is what keeps each call’s variables apart.

Common mistakes

  1. Forgetting to return. A function that computes a result but never returns it gives back None or undefined.
  2. Changing arguments by accident. Passing a list passes a reference to it, so changes inside the function show up outside.
  3. Using globals instead of parameters. A function that reads global state is hard to test and hard to reuse. Pass what it needs.
  4. Mutable default arguments in Python. def f(items=[]) shares one list across every call. Use None and create the list inside.

Check yourself

Check yourself

In def area(width, height), called as area(3, 4), what are 3 and 4?

Check yourself

A function sets a local variable x = 5 and returns. What happens to x?

Sources

  • Harold Abelson and Gerald Jay Sussman, Structure and Interpretation of Computer Programs, 2nd edition (1996), chapter 1.
  • Robert C. Martin, Clean Code (2008), chapter 3, “Functions.”

Newsletter

One new concept each week, by email.

Signup opens soon.