Friday, October 14, 2016

Declarative API Design in Swift

Benjamin Encz:

It has almost no imperative code. Most code describes network request based on instance variables and previous requests.

It doesn’t call the networking layer, nor does it have any knowledge of the type that actually performs the upload. It just describes the intent of each request. In fact, the code has no observable side effects at all, it only mutates internal state.

There is almost no error handling code here. The responsibility of this type is only to handle errors specific to this request sequence (e.g. missing required data from a previous request). All other errors are generically handled in the networking layer.

With the old version:

Separation of concerns was a lot harder to come by. Instead of simply describing a request sequence, the NSOperations in the NSOperationQueue themselves were responsible for kicking off a network request. This promptly introduced a bunch of other responsibilities such as request cancellation and error handling. While similar code had been implemented in other places that dealt with creating upload requests there was no good way of sharing that implementation. Subclassing wasn’t an option since most upload requests were modeled as a single NSOperation, while this upload request sequence was modeled as an NSOperation that wrapped an NSOperationQueue.

Comments RSS · Twitter

Leave a Comment