6 ms·
I would say this is why monads such as Either, and Optional, are so important. They require the programmer to deal with the dark path or at least make it expli
by ishjoh 7y ago
I would say this is why monads such as Either, and Optional, are so important. They require the programmer to deal with the dark path or at least make it explicit when there is a dark path. I first encountered these monads writing Scala years ago, and although it takes some getting used to, I always use them now in my Java day job to communicate the dark path.
- taeric 7y agoEither fails at that, though. Yes, the programmer had to explicitly pull out one of the branches. Nothing guarantees the other branch was looked at, though. And with how it affects code, it is easy to read past where someone had a possible error and just ignored it.
- shawnz 7y agoWhat advantage does this approach give over Java's checked exceptions, which have support built right into the language already?
- joshlemer 7y agoNot saying using Either is pure win, but I think a lot of the benefits of the approach is that it's a lot more flexible for different actions you may want to take in response to errors. If you can reify the "throwing an exception" action as data (in this case, `Left(error)` then you can very easily for instance collect a bunch of these errors in a list or something, or perform other transformations. Or maybe you have a collection of data to perform work on, and only on the data that was associated with an error do you want to report, and the data that was not associated with an error, you want to process normally. It may be hard to write code that's flexible enough for all of these use-cases in a style that deals with errors by throwing exceptions up the call stack, but your mileage may vary.
- darkkindness 7y agoEither and try-catch are basically the same thing, except try-catch is, as you say, baked into the language, while Either is just data, a value you can manipulate however you want. Usually they will have the same functionality, but in some cases Either gives a few distinct advantages (off the top of my head): - You can work a list of Either values (Lefts and Rights). For example applying a readFile operation on a list of file paths can give you a list of Lefts (errors) or Rights, which you can handle later. I can't imagine doing that cleanly with try-catch (i.e. without building up some intermediate list). - Can return whatever data you want in the error, rather than just a String message (or, I guess you can if you write some custom CheckedException, but Either saves you from having to do that every time)