Skip to content
This repository has been archived by the owner on Feb 8, 2021. It is now read-only.

Replace force unwrapping with failable initializer #31

Conversation

morganchen12
Copy link
Contributor

Better supporting the unhappy path of failure by producing a nil model object instead of a non-nil model object with all of its fields set to nil. This also allows for non-optional model fields without the risk of runtime errors.

@hkellaway
Copy link
Owner

Thinking alike here! This recent PR changed to using init(json:): #30

It doesn't introduce a failable initializer, so that's definitely something to consider. Do you want to update your PR to just reflect the failable initializer?

@morganchen12
Copy link
Contributor Author

Yeah, just squashed a bunch of merge conflicts. Not perfect yet though, still got some issues.

@morganchen12
Copy link
Contributor Author

Should be good now.

@hkellaway
Copy link
Owner

I see you're advocating for a failable initializer over a force unwrap operator. I see virtue in both - can you let me know why you think failable initializer is the way to go?

@morganchen12
Copy link
Contributor Author

When serializing concrete model objects from arbitrary data, it's usually a given that not all data will result in a valid model object. In this case, it makes sense to return nil from the initializer as an indicator of failure, rather than returning a non-nil model object with all of its fields set to nil. In the case where some fields are essential and must not be nil (i.e. a User model fetched from a remote database somewhere might not make sense without its unique id), a failable initializer allows us to express this requirement as a non-optional field without the use of force-unwrapping, which as you know is crashy and frowned upon.

The init? definition in the protocol doesn't forbid adopters of that protocol from defining a non-failable initializer, it just indicates that some serialization may fail.

@hkellaway
Copy link
Owner

i have been thinking about this all day; i'm liking the failable initializer for safety. this will come in the release after the latest i've prepared - will ask for a rebase then

thanks! ✨

@hkellaway hkellaway added this to the 0.5.0 milestone Aug 21, 2015
@hkellaway hkellaway changed the title Feature/morganchen12/failable initializers Replace force unwrapping with failable initializer Aug 21, 2015
@morganchen12
Copy link
Contributor Author

Hm, looks like the code examples in the README may need to be updated as well.

@hkellaway
Copy link
Owner

in progress

@hkellaway
Copy link
Owner

Replacing this PR with rebased version: #38

@hkellaway hkellaway closed this Aug 22, 2015
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants