5 ms·
A great post! A suggestion for change: Try[V] is, for most purposes, a more intuitive alternative to Either[V, T] for exception handling. It can be passed a bl
by azernik 11y ago
A great post!
A suggestion for change: Try[V] is, for most purposes, a more intuitive alternative to Either[V, T] for exception handling. It can be passed a block that may throw a Throwable and Do the Right Thing, it has functions named in ways that make it more clear which alternative they operate on (recover, isFailure, isSuccess), and works nicely in for comprehensions:
val tryManyThingsSequentially = for {
result <- someDangerousComputation
other <- otherDangerousComputation(result)
} yield other
(As far as I understand, it's implemented more or less as an Either[V, Throwable] under the hood.)
- bad_user 11y agoI don't agree with that advice. By using Either you're forced to enumerate all errors that can happen and those errors are no longer exceptional. This means that the ErrorType can be an ADT or even if you're using things inheriting from Throwable, you can have a base type that's more specific than Throwable. More than that, you're free to generate your own errors. Because you see, whenever you do "throw new SomeException", or in other words whenever you're using exceptions for validations of user input or flow control, God kills a kitten. The problem with exceptions is that they signal a very strong-side effect, as throwing an exception obliterates your call-stack. Forget about functional programming, because this violates the laws of structured programming, functions and modules ending up with multiple exit points, blowing up in your face when you least expect them. There's also a big difference between NumberFormatException and OutOfMemoryError. One is truly exceptional, whereas the other could be prevented, guess which is which. Btw, when using Either, as a matter of convention, the errors are at the Left, whereas the normal result is at the right. So that would be Either[Error, A]. And nothing stops you from using for comprehensions with Either ... val tryManyThingsSequentially = for { result <- someDangerousComputation.right other <- otherDangerousComputation(result).right } yield other Some people don't like Either because it is unbiased. In the Cats library you've got Xor, which is like a right-biased Either (so you don't have to use right projections explicitly, like in the above sample). There's also a similar type in Scalaz.
- azernik 11y agoWithout algebraic types in Scala, it is unfortunately very difficult to have an Either that enumerates all the expected types of exceptions from a block of code (especially one that you did not write). My general idiom for restricting the return types of Try is to recover or recoverWith only the types I consider "normal" and expected. e.g. finalTryValue.recoverWith { case FileNotFoundException => Success(HttpResponse(InternalServerError)) case JsonParseError => Success(HttpResponse(BadRequest)) case e: ComplicatedException where e.meetsSomePredicate => Failure(new MoreInformativeException(cause=e)) } // at this point, if the Try is still a failure, something's wonky and we *should* crash, or do whatever our generic error-handling code specifies // and the failure will still contain the original stack at the time of failure With regard to for comprehensions, I just find the Either left/right convention hard to read and remember; I'd even like Try if it was just a thin wrapper that added handy names to Either, like "type Try[E, V] = Either[E <: Throwable, V]" with handy aliases for left and right.
- bad_user 11y agoDon't get me wrong, I do find Try useful. We are talking about public APIs, as in APIs meant to be consumed by people other than the author of that function. The problem with a Try[T] is that if somebody else reads the signature of `def somethingDangerous()`, he won't be able to see that the code can throw a FileNotFoundException or a JsonParseError. Scala does have algebraic types and you can even handle the unexpected with a type like this: sealed trait Error case class FileNotFoundError(f: File) extends Error case class JsonParseError(path: JsPath) extends Error // ... we can even handle the unexpected case class UnknownError(ex: Throwable) extends Error Surely that's extra boilerplate, but if the function is public (meant to be used by other people), then it's worth it. Because now when you say that your function returns an `Either[Error, A]`, this type explicitly documents the important error types that can happen (and are hence not exceptional). I know what you mean by Either. What you want is a right biased Either. Many people feel that way. You've got it implemented in libraries such as Cats or Scalaz. The left/right convention isn't hard to remember, because it's consistent. In general you'll see that types are biased to the right, which really means that the useful happy path result is usually at the right.