Sunday, May 10, 2015 [Tweets] [Favorites]

Failable Initializers, Revisited

Jesse Squires:

In a previous post, I discussed how Swift’s failable initializers could be problematic. Specifically, I argued that their ease of use could persuade or encourage us to revert to old (bad) Objective-C habits of returning nil from init. Initialization is usually not the right place to fail. We should aim to avoid optionals as much as possible to reduce having to handle this absence of values.

[…]

The issues above can be addressed by removing the model’s dependency on JSON (or XML) and creating single-purpose objects for each step of the process: (1) validating the JSON, (2) parsing the JSON, and (3) constructing the model.

[…]

The combination of a phantom type and a closure property enable us to construct many unique validators, while maintaining a single generic interface through which validation occurs. In other words, we do not have to create many different concrete validators (or validator subclasses) for many different models. Additionally, in this example you can see how this brings type-safety and readability to the validator. We know that this validator is for MyModel instances.

[…]

We have divided the problem into smaller subproblems and addressed each one individually. Even better, we can now unit test each component in isolation.

Comments

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment