5 ms·
Now do one about either. Given Java 8 and Optional, I recently used Either to replace 80 something lines of crazy interconnected try-catch-bullstuff in a serve
by tetha 12y ago
Now do one about either.
Given Java 8 and Optional, I recently used Either to replace 80 something lines of crazy interconnected try-catch-bullstuff in a server with 4 straight either-based lines, "do this, in good case try this, in good case try that, ... and finally send a good result to the client, or log a bad result and send the error to the client".
Had to rework and introduce some methods to make this work, of course, but those methods turned into try { foo = doWork(); return Either.goodResult( foo ); } catch ( Exception e ) { return Either.badResult(e); }. It's structured, and neat, and readable. :)
- Dewie 12y agoEither is called Result in Rust.
- innguest 12y agoThat's a terrible name - they should change it to Either. We always call things "result" in code, but I've never called a variable "either". That's why I think Either is a better name - it's less likely to clash with valid names.
- Dewie 12y agoI agree with you on that. "Either" suggests 'either this or that', to me. "Result" feels too generic. Any value can be called a 'result'. Though I don't know what the reasoning is on the naming of that type; for all I know it might make a lot of sense within the context of rust and be very much in line with the conventions of the rest of the standard library.
- dbaupp 12y agoResult is essentially trying to only be an error-handling technique, its two variants are Ok and Err (less generic than Left/Right). I believe the 'Result' name actually comes from OCaml. Rust used also to have an isomorphic type called Either, but error handling was found to be by far the most common use of these two types, so it was decided to standardise on a single one with obvious variant names (i.e. it's clear with Ok/Err which one is the error and which one is the real value, while Either requires getting the Left/Right convention right).
- rbonvall 12y agoI remember having read that the convention was using Right when the value was right and Left for the error (the error that's left, I imagine).
- gnuvince 12y agoResult makes sense to me: you either have an Ok(value) or an Error(reason). As for the name clashing, types and values have different namespaces, so no worries there.