The Point of Optionals
What it took me a while to get was that if we encounter an API or some source of objects that is giving us an optional X, we should probably want to turn it into a non-optional X as soon as we can. We want to push the “deal with the thing not existing” code out as far to the edges of our call graph as we can, and validate things as early as we can, and as close to the source of the objects as we can. This gives us more chance to deal with unexpected situations early before they become bad, and means that the bulk of the code doesn’t have to.
I think that the loss of the mental baggage in the rest of the code will actually be substantial in many cases, and will be a great aid to productivity (plus a small aid to efficiency).
3 Comments RSS · Twitter
In a C++ codebase I'm maintaining there's a custom smart pointer type that is non-nullable. You simply can't put a null in it. It makes code easier to reason about, it clarifies who's job it is to make sure this or that is not null. But there's a few spots where the abstraction doesn't work very well, it'd need sort sort of language-level support. I'm very pleased with Swift's implementation of optionals.
Following this "debate" over optionals from a distance, I have had the impressions that an important source of complaint comes from the Cocoa frameworks that have to be cast as returning optionals in most cases, including in the Foundation framework (because traditionally, nil has been tolerated or even welcomed). The optionals then tend to be everywhere, when ideally they should rarely have to appear outside some of the UI code and the "the edges of the call graph" (nice way to put it).
@charles Yes, I think that’s a good summary. In theory, it should have been documented long ago when each Cocoa method could accept or return nil. It’s great for the frameworks that Swift is forcing Apple to examine the cases more closely. I am slightly worried about crashes due to improperly typed framework methods, though—i.e. if a method returns a non-optional that is actually nil, code on the Swift side will blow up.