9 ms·
The power of Result types in Swift
- Smaug123 8y agoI've seen this referred to as "railway programming", and there's a wealth of explanation over at https://fsharpforfunandprofit.com/rop/ https://fsharpforfunandprofit.com/rop/. In particular, the slide deck from the FP eXchange contains a diagram (slide 75 out of 154) with a happy path along the top, and a sad path along the bottom, and at every stage when you `bind` a Result into an existing Result, you have the opportunity to divert into the sad path. Neat little metaphor.
- pbiggar 8y agoWe're planning on using a similar strategy to ROP in Dark (https://darklang.com https://darklang.com). My suspicion is that editor support for "happy path programming" can make a huge difference in how easy it is to write safe code.
- mpweiher 8y agoWhat I found interesting is that if you have a pipe/filter architectural style, your happy path stays completely free of error handling, because when a filter doesn't have a good result, it just doesn't pass any data to the next filter in line. Done! You can then centralize the error handling by having a "stderr"-like output on your filters. When you have a call/return architectural style, you need to return something, and thread the result along, making things more complicated.
- singularity2001 8y ago>> if you have pipes/filters, you stay free of error handling: when a filter doesn't have a result, it just doesn't pass any data to the next filter in line. That is an important root insight. It also applies to for loops, and could apply to switch statements switch result { case something: break case none: error: empty: default: //? }
- lmm 8y agoI find this concept of a "stderr output" far more complicated. What's next, a "controlling terminal"? Values are much easier to reason about and inspect than functions, so it's better to have simple functions that return complicated values than to complicate the functions themselves.
- mpweiher 8y ago> I find this concept of a "stderr output" far more complicated. And you know this how? > Values are much easier to reason about and inspect than functions Right, which is why we want to avoid functions as much as possible. > simple functions that return complicated values than to complicate the functions themselves Fortunately, these filters aren't functions, so this doesn't complicate them, it makes them simpler.
- lmm 8y ago> And you know this how? Professional experience. > Fortunately, these filters aren't functions, so this doesn't complicate them, it makes them simpler. Functions are at least restricted enough that you can sort of reason about them. If these things are not even functions then there's no hope of ever understanding them.
- dep_b 8y agoIt's not exactly the same as railway programming as in Swift it's typically not used to connect functions together but rather to replace separate callbacks with one "result" function and to hard type certain results. One typical case in Objective-C style API's would be: - (void)fetchData whenDone finished: [a block] ifFails failed: [another block] Or: - (void)fetchData whenDone finished: [a block that has nullable Data and nullable error as parameters] Both approaches had problems. The first one uses two result blocks, but you want to do a lot of the same stuff usually, like: * Stop the spinner * Enable the send button again This often lead to repetitive code or a maze of function calls. The second one made you basically duck type for the kind of response it really was. Does it have an error? It probably failed. Does it have data? It probably worked. But what if it has both data and an error (error data?) or simply both values were nil? Brittle code. While I really like the railroad approach the typical problem area Swift is applied to (often web API driven iOS and macOS applications) simply don't lead to these huge chains of functions. I'm definitely going to try it for backend code though.
- nine_k 8y agoYou don't need huge chains. Also, compare it to the interface of Futures.
- bonesss 8y ago> web API driven iOS and macOS applications) simply don't lead to these huge chains of functions I agree you don't see them collected together, as a rule, but if you follow Results<> like this in those domains you see them being used multiple times on the backend before being yeilded to the frontend for further handling, resulting in chains that are just spread out a little bit more. Personally I've started exposing them through JSON at the API level to further extend the systems explicitness and idempotency.
- _pmf_ 8y agoI refuse to see where the difference to exception handling is. My exceptions bubble up to my "sad path" handler.
- Smaug123 8y agoYour phrasing ("I refuse to see…") makes me very apprehensive of trying to explain, but I'll bite. Using exceptions is dealing with errors out-of-band. Using Result types is dealing with errors in-band. In-band is somewhat less flexible because you don't have the power to arbitrarily alter the execution flow of your program. Out-of-band is much easier to reason about by that very token.
- deleted 8y ago[deleted]
- m3kw9 8y agoThis only pushes the responsibility down lower in the stack. Somewhere someone would have to handle a state where we have data and error being nil at the same time.
- minfduck 8y agoNo it doesn't. This article is specifically about how you can use the Swift type system to prevent that from happening. You get a compile time guarantee that the result will either be data or error.
- m3kw9 8y agoThe server can a aboulutly send you data and error as nil, either by error or on purpose. Someone is gonna handle that.
- cnowacek 8y agoNot necessarily. The way that the enumerated type is declared, the associated types of the success and failure values are declared to be normal (not optional). This restricts nil from being passed in as the data or the error.
- solidsnack9000 8y agoActually, it puts the responsibility higher in the stack. The first error effectively terminates the computation, so subcomputations can ignore them and the caller can decide what to do with them. One good thing about this is not having to push down anything to do with logging or reporting into subcomputations.
- solidsnack9000 8y agoIt seems like a major legacy of practical experience with FP in the 200x and 201x years is going to be result types.
- nine_k 8y agoAlso, the idea of mapping and folding, which is now everywhere, and is not limited to traditional collections. (Likely applicatives will take another decade to go mainstream.)
- solidsnack9000 8y agoThe 4th generic added to Go will be our memorial. Erring[ResultType]
- javier2 8y agoWouldn't that be the day. The funny part is how they preached 'errors are values', and instead of giving a good error monad, they implement a poor version of it explicitly where they feel like it.
- lmm 8y agoEvery decade mainstream programming culture finally picks up one feature from ML.
- solidsnack9000 8y agoTechnology is spreading much more quickly than training so it makes sense. ISWIM was written up in the fifties.
- khitchdee 8y agoWhile typing is a good way to reduce programmer errors, specially for large scale programs, it's much like autocomplete in a word processor. It's cool to have but also a bad habit to form. The quality of prgrams would improve if such aids were reduced and the programmer was expected to form good programming habits instead.
- joncfoo 8y agoMaybe a quick spell check would've caught the misspelling of prgrams or maybe more proof reading is the answer. /s :D Types are a tool just like auto spell checking. Why not leverage them to reduce cognitive load?
- taeric 8y agoAmusing example, since my phone's autocorrect seems quite often to increase my cognitive load.
- drb91 8y agoWhat would a typeless language look like?
- khitchdee 8y agoC. Just basic data types.
- drb91 8y agoC is in no way typeless. Furthermore, i would expect a well behaved dev to avoid c at all cost.
- khitchdee 8y agoWell, this article is about Result types in Swift, and my point is, I think this kind of thing is overkill. It tends to make the learning curve for a new programmer steeper because there's all these extra bells and whistles provided by the language that have to be learnt before you can get going, and then you have sample code and tutorials and so on. Learning and using C was and is a lot simpler than say Swift.
- hannofcart 8y agoIt's a very well written article. I'm just a bit surprised there is no mention of the origins of this paradigm as it originated in functional languages (Maybe monad in Haskell).
- dwaite 8y agoI think it’s closer to Either
- KirinDave 8y agoWell, Either is a monad. Evolution of this style to avoid divergent nesting depths (The Codoken: http://i.imgur.com/BtjZedW.jpg http://i.imgur.com/BtjZedW.jpg) is a monad, even in the "railway" style of F#.
- wool_gather 8y agoThis isn't Maybe. Optional in Swift is Maybe.
- hota_mazi 8y agoNo, `Result` is more like the `Either` monad.
- KirinDave 8y agoThe tricky part of this approach comes when you extend it. Let's say we have two functions and we'd like to combine them and return a third. typealias Handler1 = (Result<Data, LoadError> -> Void) typealias Handler2 = (Result<Address, IndexError> -> Void) func load(addr: Address, then handler: @escaping Handler1) { ... } func lookup(name: string, then handler: @escaping Handler2) { ... } // What would the type of Handler3 be? func loadDefault(then handler: @escaping Handler3) { lookup("default") { result in switch result { case .success(let address): load(address) { result2 in switch result2 { case .success(let data): // Happy path case .failure(let error): // We have a load error for handler3 } case .failure(let outerError): // ERROR: We have a lookup error for handler3 } } } // P.S., don't complain about syntax I really don't know swift :P Handler3's type is actually the sum of LoadError and IndexError. This is sort of a non-trivial problem for a lot of use cases of Either. Monadic and Railway Either programming typically solve this problem by saying, "Fine well then every single Either/Result in the chain needs to be of the same type, which includes a unified error type." In this article's case, I guess we could appeal to Swift's binding to FoundationKit to lift up NSError? Sure! That'll compile! Maybe there is a Compound Type thing? It will probably compile but it'll shape your handler in weird ways. It still seems pretty unsatisfying. The point here was to make it easy to work out what errors we should handle, but now we need an explosion of combination types (unique to each call graph in this case, wow!) Modern Haskell, which along with ML pioneered these style of, has some slick type machinery tricks to deal with this that are not well supported yet (even type lists are not a slam dunk because we need something that's order-insensitive). Most folks will be required to make a new ad-hoc sum type (like Result, but EitherError<Error1, Error2>), and then have to pattern match on that to handle errors. But at the end of the day, even Haskell with all its principle has try/catch statements in IO and an exception hierarchy. In fact, it's considered best practice for production code to avoid giving the appearance that Either can capture all your errors (since it seldom can): https://www.fpcomplete.com/blog/2016/11/exceptions-best-practices-haskell https://www.fpcomplete.com/blog/2016/11/exceptions-best-prac... Which is not to say Either's (and Railway programming's) "Sum-type errors") aren't a substantial improvement over special return values or Common Lisp/Go's product-style return values. They are. But sadly they can't really get you away from exception handling when you start interacting with the "real" world as the examples here do. It's a win for things like HTTP responses or decoding libraries.
- jordansmithnz 8y agoThe reason I started using this pattern is one I didn’t see the article mention: With legacy style result callbacks, you’ll have both an optional value and an optional error returned - this corresponds to four possible states. If I’m using an API returning this, I have to think about two cases which probably won’t happen (neither an error or value, or both an error and a value). I’d like to think the API I’m using wouldn’t return those states, but since it’s not typed as such then code I’m writing should probably handle those cases gracefully. By using a result type as per the article, it is well defined that only two states are possible. This pattern is a really nice one, and is a great use of Swift’s associated value enums.
- zoul 8y agoTo nitpick, the “both error and data” can happen, for example when the connection drops in the middle of a large response. Probably doesn’t change anything, but it’s good to know, maybe so that you don’t trap on an unexpected combination.
- sghiassy 8y agoHow would the explicit case of success/fail for an API response compare to the Promise pattern?
- sghiassy 8y agoSeems perhaps the Promise pattern is more conducive for composition, aggregation, etc of multiple asyncs? Or are they just two different problem domains?
- krzat 8y agoResult will likely not appear in standard library, because it duplicates functionality of do/try/catch and async/await
- _31 8y agoAnother great article on swiftBySundell. I really enjoy these well written deep dives into Swift.