Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling monads in Scala? Try vs Validation

scalaz.Validation is said to be more powerful than the Try monad, because it can accumulate errors.

Are there any occasions where you might choose Try over scalaz.Validation or scalaz.\/ ?

like image 626
James McCabe Avatar asked Feb 09 '14 19:02

James McCabe


1 Answers

The most significant argument in favor of Try is that it's in the standard library. It's also used in the standard library—for example the callbacks you register with Future's onComplete must be functions from Try. It may be used more extensively in the standard library in the future.

The fact that it's in the standard library also means it'll look familiar to more people. You'll probably tend to find it in more of the third-party libraries you use. And of course sometimes you may not be allowed to use Scalaz (or any other dependencies) or may want to avoid Scalaz for other perfectly good reasons.

Other stuff: I can't remember the last time I wrote a \/ that didn't have Throwable on its left side (I have—it's just not something I do often). Try bakes this in, so you don't have to worry about writing an alias or whatever.

As senia notes in the comments above, there's arguably something a little unintuitive about biasing an either-like type but still using the language of "left" and "right" (as \/ is, and does). Why does \/ bind through the right side? Because it does, that's why. I personally don't find the naming that objectionable, but I can understand why some people might. Try avoids the issue by having constructor names that clearly indicate their semantics: Success and Failure, not Left and Right or -\/ and \/-.

Now that we're getting to the completely superficial and subjective reasons to use Try, some people may just think \/ and -\/ and \/- are ugly. I generally don't mind operator-heavy code, and I find the jumble of slashes and dashes really unpleasant to type and read.

So those are some arguments in favor of Try, as requested, but I'll conclude by saying that I never use it, myself. I don't specifically care all that much about the fact that it violates the monad laws (although I can understand why people do), but I do find \/ and Validation much less ad-hoc and easier to reason about, and I like having access to both (Validation when I want to accumulate errors, \/ when I need monadic sequencing) in a single framework.

like image 141
Travis Brown Avatar answered Nov 17 '22 00:11

Travis Brown