Swift Functional Programming: Pure Functions
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.
- Create values for the arguments.
- Call the function.
- Assert the function returns the correct value.
Unit testing the updateContactInfo
function would be painful. You would have to perform the following steps:
- Create an instance of the data structure that contains the contact information.
- Create, mock, or stub three text fields.
- Provide text for the three text fields.
- Call
updateContactInfo
. - Assert the name, address, and phone number are correct.