Notes Tutorials

Functions: input, output, side effects

What goes into a function, what comes out, and what else it changes along the way. Parameters, return values, how arguments are passed in Python, JavaScript, PHP, and Go, and why pure functions are easier to trust.

6 min readAlso available in Bahasa Indonesia →

In part 0 we met the three moves of programming: primitives, combination, and abstraction, giving a piece of work a name. Functions are the main way we do that. This part looks at a function as a small machine with three things to watch: what goes in, what comes out, and what else it changes along the way. That third one, side effects, is where most of the interesting bugs live.

Input and output

A function takes parameters (the names in its definition) and receives arguments (the actual values passed in a call). It gives back a return value.

def with_tax(price):        # price is a parameter
    return round(price * 1.11)

total = with_tax(100)        # 100 is the argument; total is 111

If a function doesn’t return anything explicitly, most languages still give something back. The Python tutorial says “even functions without a return statement do return a value, albeit a rather boring one. This value is called None”:

def greet(name):
    print("Hello,", name)

result = greet("Rama")
print(result)
Hello, Rama
None

That’s a common beginner bug: a function that prints a result instead of returning it. It looks fine in the terminal, but the caller gets nothing to work with. As a rule, return values and let the caller decide what to print.

Returning more than one thing

Sometimes a function needs to say two things: the result, and whether it worked. Go builds this into the language. Effective Go: “One of Go’s unusual features is that functions and methods can return multiple values.” The common pattern is a value plus an error:

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}

result, err := divide(10, 4)   // 2.5, nil
_, err = divide(1, 0)          // error: division by zero

Python and JavaScript can return a tuple or an object to the same effect, and PHP can return an array. Error handling gets its own part later in the series.

How arguments are passed

When you pass a variable into a function, does the function get the variable itself, or a copy? This is where part 3 on values and references pays off, because each language answers slightly differently.

Python. The tutorial: “arguments are passed using call by value (where the value is always an object reference, not the value of the object).” In practice: a function can change a mutable object you pass in, but can’t make your variable point at something else.

def rename(user):
    user["name"] = "Budi"        # changes the shared object

def replace(user):
    user = {"name": "Sari"}      # only rebinds the local name

u = {"name": "Rama"}
rename(u);  print(u)             # {'name': 'Budi'}
replace(u); print(u)             # {'name': 'Budi'}  ← unchanged

JavaScript behaves the same way. MDN: “Parameters are essentially passed to functions by value”, but “When you pass an object as a parameter, if the function changes the object’s properties, that change is visible outside the function.” The same rename/replace pair in JavaScript prints Budi both times.

PHP is different for arrays, because arrays are values. “By default, function arguments are passed by value”, so a function gets its own copy:

function addItem(array $items, string $item): array {
    $items[] = $item;
    return $items;
}
$list = ["a"];
$new = addItem($list, "b");
echo json_encode($list), " ", json_encode($new);   // ["a"] ["a","b"]

“To allow a function to modify its arguments, they must be passed by reference”, by putting & before the parameter name:

function addItemRef(array &$items, string $item): void {
    $items[] = $item;
}
addItemRef($list, "c");
echo json_encode($list);   // ["a","c"]

Go copies values too, but a slice is a small descriptor pointing at shared data, so a function can change the elements:

func double(nums []int) {
    for i := range nums {
        nums[i] *= 2
    }
}
nums := []int{1, 2, 3}
double(nums)
fmt.Println(nums)   // [2 4 6]

You don’t need to memorize all four. The habit that matters: when you pass something into a function, know whether the function can change it, and say so in its name or documentation.

Side effects

A function has a side effect “if it has any observable effect other than its primary effect”, that is, anything beyond computing and returning its result. Common side effects:

  • printing or logging
  • writing to a file, a database, or an API
  • changing an argument that was passed in
  • changing a global or module-level variable
  • reading something that changes on its own: the current time, a random number, user input

Side effects aren’t bad. A program without them couldn’t save anything or show anything. The problem is side effects you don’t expect. Here’s a small example with a big consequence:

def add_tax_in_place(cart):
    for item in cart:
        item["price"] = round(item["price"] * 1.11)
    return cart

cart = [{"name": "book", "price": 100}]
add_tax_in_place(cart)
add_tax_in_place(cart)     # called again somewhere else...
print(cart)
[{'name': 'book', 'price': 123}]

Tax was applied twice, because the function changed the cart instead of returning a new one. Each call is fine on its own; the bug only appears when two parts of the program both call it.

Pure functions

A pure function has two properties: “the function return values are identical for identical arguments”, and “the function has no side effects”. The tax function written that way:

def with_tax(cart):
    return [{**item, "price": round(item["price"] * 1.11)} for item in cart]

cart = [{"name": "book", "price": 100}]
print(with_tax(cart), cart)
[{'name': 'book', 'price': 111}] [{'name': 'book', 'price': 100}]

The original cart is untouched, and calling it twice gives the same answer twice. Pure functions are:

  • Easy to test: give an input, check the output. No database or setup needed.
  • Easy to reuse: they don’t depend on or disturb anything around them.
  • Safe to cache: the memoization from part 6 only works because fib is pure.

A practical way to combine both worlds: keep the decisions and calculations in pure functions, and push the side effects (reading the request, writing to the database, sending the email) to a thin layer at the edges of the program.

Habits for writing good functions

  • One job. If you need “and” to describe what a function does, it’s probably two functions.
  • A name that says what it does. Verbs for actions (send_invoice), nouns or questions for values (total_price, is_overdue).
  • Few parameters. More than three or four usually means some of them belong together in an object.
  • No boolean flags that switch behavior. save(user, True) tells the reader nothing. Two functions with clear names are better.
  • Return, don’t print. Let the caller decide what to do with the result.
  • Make side effects obvious. A function called calculate_total should not also send an email.

Why this matters day to day

  • Double-applied changes. Discounts, taxes, and stock adjustments applied twice are classic production bugs, and they almost always come from functions that modify their input.
  • Tests. Code full of side effects needs databases and mocks to test. Pure functions need two lines.
  • Switching languages. The same “pass this array into a function” means a copy in PHP and a shared object in Python and JavaScript. Knowing which is which saves hours.
  • Reading code. A good function name plus no hidden side effects means you can understand a call without opening the function.

Try it yourself

  1. Write a function that prints a total, then change it to return the total. Use it in two places.
  2. In PHP, write a function that adds an item to an array, once without & and once with it. Print the original array after each call.
  3. Take the add_tax_in_place example and rewrite it as a pure function. Call it twice and compare.
  4. Find a function in your own code that does more than one job. Split it into two.

Summary

  • A function has inputs (parameters), an output (return value), and possibly side effects.
  • Functions without return still return something (None in Python). Return values instead of printing them.
  • Go returns multiple values, commonly a result plus an error.
  • Python and JavaScript pass object references by value; PHP copies arrays unless you use &; Go copies values but slices share data.
  • A side effect is anything observable beyond the return value; unexpected ones cause the worst bugs.
  • Pure functions return the same output for the same input and change nothing else, so they are easy to test, reuse, and cache.

References