Blog

Swift Tip: Extracting Pure Functions

In Swift Talk #103, Refactoring Large View Controllers (a public episode), we extract two pure functions out of an existing view controller. We chose to use the Wikipedia iOS app because it’s a large, well written, and open-source application.

In the PlacesViewController, there is a method that computes whether or not two regions are significantly close to each other: isDistanceSignificant(betweenRegion:andRegion:)

class PlacesViewController /* ... */ {
    func isDistanceSignificant(betweenRegion searchRegion: MKCoordinateRegion,
        andRegion visibleRegion: MKCoordinateRegion) -> Bool {
        // ...
    }
}

If we look at the method signature in isolation, we can’t determine whether it uses the state of PlacesViewController. Fortunately, in this case it doesn’t, so we can move it out of the class and it will still work.

By moving the method out of the view controller, we make it completely obvious that it is independent of any state in the view controller. We can now test it in isolation, without having to instantiate the view controller (and its many dependencies).

To test it, we pass in the required parameters and verify the result. When you have a pure function like isDistanceSignificant(between:andRegion:), this is all you need to do for a test, there is no state to set up.

In MVC, the view controller has a lot of state and dependencies: the model, the view hierarchy, and all of its own properties. This makes code inside the view controller both difficult and slow to test, regardless of whether you’re testing manually or with unit tests.

Locating functions that can be extracted from the view controller can make those functions much easier to test, and you’ll be making your view controller just that little bit smaller — a win-win. 😊

For a second example, keep watching! We go on to refactor a method that adjusts the frame of a subview, and extract almost all its code into another pure function.

Thanks to the support of our subscribers, the first episode in this series is public. To follow the rest of this series, become a subscriber.


Stay up-to-date with our newsletter or follow us on Twitter.

Back to the Blog

recent posts