6 ms·
Is it crazy if I think that first example is the most readable of the three? In fairness, I've done a lot of work in TS and exactly none in Rust, so this is to
by ketzo 6y ago
Is it crazy if I think that first example is the most readable of the three?
In fairness, I've done a lot of work in TS and exactly none in Rust, so this is totally biased, but at the very least, it seems like all you're getting in the next examples is two fewer lines of code, in return for assuming that the reader is familiar with 1) `Option<x>` 2) `.ok\_or` 3) the syntax of the third block which I don't remotely get.
Genuine question, how comparable are these things to understanding "File | null" in TS, which I would consider day 1 learning?
- richardwhiuk 6y agoThe former code is more equivalent to: let file = match file { Some(file) => file, None => panic!("file was null"); };
- timidger 6y agoWhich you'd never write in practice since `expect` exists
- vikiomega9 6y agoCan you say more here, I don't have the context.
- steveklabnik 6y agoThis code is identical to let file = file.expect("file was null"); That is, the "expect" method does exactly this.
- jeswin 6y agoI like Rust from what I've tried. But I'd have preferred something like this: let file = file.unwrapOrPanicWith("file was null"); option.expect(message) doesn't semantically make sense.
- jack1243star 6y agoI read it as expect (prepare) for the worst!
- steveklabnik 6y agoThere was some discussion about this when the method was named; you're not alone. In the end, it is what it is. You could define your own method like that if you really wanted to.
- fuzzy2 6y ago> Is it crazy if I think that first example is the most readable of the three? No. That's simply the difference between imperative and functional code. If you don't know the latter you could never understand this. For the most part, the last example is equivalent to `let result = file && parse(file);`, but there are important differences to consider in JavaScript at runtime.
- ketzo 6y agoInteresting, okay, makes sense. Thanks for the explanation.
- hardwaregeek 6y agoI realize the shadowing might make the Rust example unnecessarily confusing. With overly pedantic names, it might look like: fn parse_file(file_from_input: Option<File>) { let file = file_from_input.ok_or(Error::new("File must exist"))?; } What I like about the Rust version is that it explicitly unwraps the argument and assigns it to a new variable. In the TypeScript one, the if statement allows the inference algorithm to determine that `file` is a `File` and not a `File | null`. That's a testament to the TypeScript team's efforts, but it's a little less ergonomic (in my view) that variables can change their type without getting mutated or changed in any way. For instance, if I were to open up this file in emacs with no language server, nothing. I'd have to trace over the file and act like the TypeScript checker, thinking "oh okay so this null check ensures that file cannot be null, therefore it's inferred as File". This is clearly simple, but for other cases it's not as easy. Whereas with the Rust code, I know that my argument, file_from_input is an Option<File>. file_from_input.ok_or(Error::new(..)) makes it a Result<File, Error>. The (?) macro makes it a File. Each step produces a consistent type. At no point do I have to understand the inference algorithm to determine what the type may be. That said it's totally cool if you find the TypeScript version more readable :D. It's not my place to say what's readable or not readable to you.
- brianpan 6y agoAgree. It's more about the usefulness of moving to the non-Optional type and the null safety in following lines, rather than the readability of the ok_or.
- stouset 6y ago> Is it crazy if I think that first example is the most readable of the three? IMO, sort of! All abstraction requires you to understand it at some level before you can quickly reason about it in code. But once you do, it allows you to reason about things at a higher level, rather than at a level where you have to focus on each detail individually. This is a net win for good abstractions that are (generally) simple and minimally leaky, but it can be a net loss for abstractions that are complicated. You see this same conversation play out with functional looping constructs vs. imperative ones. Which is more readable? for (int i = 0; i < a.len(); i++) { a[i] = 0; } // vs. a.map! { 0 } If you don't know what `map!` does, the former. And many people argue for this for the sake of "simplicity". But when you understand functional iteration—which is generally a simple, non-leaky abstraction—the latter wins by a mile. And while you might look at this example and think "you're just saving a few lines of code", the latter not only completely eliminates entire classes of problems (off-by-one errors, slow calculation of `len()` for e.g., NUL-terminated strings, etc.) but knowing it also unlocks a bunch of additional useful tools like `reduce`, `filter`, and friends that reduce reams of boilerplate throughout your code while dramatically improving comprehensibility. The same is true of `Option<T>` and `Result<T>`. They're wildly powerful and allow for rapid understanding of code without having to read and parse if-else branching to confirm that the logic is performing null checking or error handling (and more importantly, doing it correctly). So you're not crazy for thinking the first example is the most readable of the three given your current knowledge. But you are crazy if you think the first example is preferable to learning the relatively simple abstractions of Option<T> and Result<T> which allow reasoning about things at a higher level and unlock extremely powerful tools in doing so.
- millstone 6y agoA counterpoint: Option and Result are hard to read and unpleasant to work with. They are so annoying, that the language designers extended the language itself to make them tolerable - do notation in Haskell, '?' operator in Rust, guard-let in Swift. A plain old for loop has so much to recommend it. You get powerful control flow constructs (break/continue/return) and obvious performance characteristics. Can you tweak your function to stop filling the first time a zero is encountered? That's a simple one-line change with the for loop, but a puzzle for the functional iteration.
- woah 6y agoIt is the most readable to you because you are used to null. If you're reading Rust, then it's a pretty good assumption that you'll be used to Option<x>. Null is sloppy because it is the only way in many languages to express something like a union type (in Rust terms, an "enum"). So it gets overloaded to convey information that would be more accurately conveyed by a union type. The Rust equivalent of null, Option, is just another enum and you can handle it with the standard enum tooling the language gives you such as pattern matching. It also makes you stop and think about what you are doing if you're returning it. In most cases, your intent can be more clearly expressed with an enum other than Option. This contrived example would be less likely to appear in Rust. Why is there a function called parseFile taking something that might not even be a file? As an aside, the Rust code could also be written like this: fn parse_file(file: Option<File>) -> Result<(), String> { if let None = file { return Err("File must exist".into()); } // ... }
- phiresky 6y ago> As an aside, the Rust code could also be written like this Sadly it can't really, because Rust doesn't have control-flow based type refinement like TypeScript.. In TS the type of `file` after the throw is File. In Rust it stays `Option<file>` so you would have to unsafely unwrap it below the if block.
- mikepurvis 6y agoRust’s if-let construct handles that in a nice, explicit, and compact way.
- steveklabnik 6y ago(Unwrap is not unsafe, and in fact, in this code, you would even know that it can never panic. That being said, you're not wrong that this is nicer in TS. You could invert the condition and add an else and it would be not too terrible. I'd still probably go for a ? style.)
- colejohnson66 6y agoWhy use `if let None = file` instead of `if file.is_none()`?
- lmm 6y agoThe block syntax is comparable to understanding File | null - it's day 1 learning in Rust. The part I'd say you're missing is that Option is just a plain old type and ok_or is just a plain old function, so if you don't know what they're doing you can always just click through to their definitions (which are in normal plain old code) and read them. Even if you don't do that, you know that they're not doing any magical control flow things. Whereas to understand the first example I have to understand what "if" does and how having a bunch of statements after each other works, and there's nothing to tell me that anywhere.