Swift Functional Programming: Pure Functions

January 15th, 2018

Filed under: iOS Development, Mac Development | 2 comments

A pure function doesn’t reference any data outside of the function. If you supply a given input to a pure function, it always returns the same value. The following is a simple example of a pure function:

func increment(value: Int) -> Int {
    return value + 1
}

The increment function is pure because it increments the value you supply to it. It doesn’t modify any outside variables. If you pass the value 9 to increment, it always returns 10.

The following code is a hypothetical example of an impure function that updates contact information based on the values of text fields in an app’s user interface:

func updateContactInfo() {
    name = nameTextField.text
    address = addressTextField.text
    phone = phoneTextField.text
}

The updateContactInfo function is impure because it modifies variables outside of the function: name, address, and phone.

Pure Functions Simplify Unit Testing

A big advantage of pure functions is they’re much easier to unit test. To test the increment function, all you have to do is create an integer, call increment, and assert the incremented value is correct.

I know increment is a simple function, but unit testing any pure function follows the same steps.

  1. Create values for the arguments.
  2. Call the function.
  3. Assert the function returns the correct value.

Unit testing the updateContactInfo function would be painful. You would have to perform the following steps:

  1. Create an instance of the data structure that contains the contact information.
  2. Create, mock, or stub three text fields.
  3. Provide text for the three text fields.
  4. Call updateContactInfo.
  5. Assert the name, address, and phone number are correct.
Facebooktwittergoogle_plusredditmail

Tags: ,


2 thoughts on “Swift Functional Programming: Pure Functions

  1. Christian says:

    Hey,

    Did you figure out how to approach pure functions that are composed of other pure functions? Unit testing each of them is simple, but testing the composite itself isn’t. (Unless you inject the parts as closures, which is kind of odd.)

    Cheers,
    Christian

  2. Mark Szymczyk says:

    Christian,

    I haven’t figured that out yet. Maybe someone else reading this post will have an answer for you.

Leave a Reply

Your email address will not be published. Required fields are marked *