We are building a mobile app for enterprise asset management. One of the methods in our SyncManager class had a very complex merge method that merged the items in core data and the items received from the server. To give you a perspective this is what the method looked like.
This method takes in sorted business objects (Work Orders) from core data as the first argument and sorted JSON array on work order id as the second argument and does swift’s equivalent of pointer increments to merge these lists together. The code has two vars and three while loops. While the code works per se, reasoning about a bug by say forgetting to increment a pointer is very hard.
The goal for our refactor is zero vars and a functional way to subtract the lists based on object keys. This is what the transformed functional code looks like.
By most measures, the refactored code looks a bit better than the original. We have removed a lot of complexity from various branching and looping and have made the interface consistent and readable.
Swift does not provide the
indexUniqueOn methods. I wrote a bunch of functions for extending the SequenceType.
The subtract method takes in another collection and two lambdas that lets it arrive on the common key. This lets us subtract items of one sequence based on the one of the derived keys of the other sequence. The Swift’s type system lets us set constraints on generics that help us express this beautifully. Swift’s type system is actually quite nice. And this is what the tests for the extension look like.