260 points · by tosh · 8y ago · 160 comments
You can then centralize the error handling by having a "stderr"-like output on your filters.
When you have a call/return architectural style, you need to return something, and thread the result along, so you need to do something more complex like this pattern.
You can then keep your call/return architectural style or use pipes/filters. Haskell and F# are pretty good at providing ways of describing these things mathematically and making them easy to compose, it's just that the underlying math is obscure enough that we get blog posts about it. Fortunately, there are enough mature libraries that you don't need to understand the math to leverage this stuff.
What's the "pattern I've always used"?
Anyway, the problem is one of call/return in general, whether expressed in an FP language or not. It really wants to return something. With a real dataflow approach, that just goes away. And nothing is simpler than something.
The pattern is to return a value and have some non-local return for errors. For example, having a return value in C++ but throw an exception for errors. By "always used", I'm just asserting that most people are familiar with this pattern and use it frequently.
> Anyway, the problem is one of call/return in general, whether expressed in an FP language or not. It really wants to return something. With a real dataflow approach, that just goes away. And nothing is simpler than something.
This is not true for languages like Haskell. When you are writing monadic functions, it doesn't "want" to return something, instead, you are free to create your own data flow primitives as the monad's interface. This lets you change how control flow works in these monads while providing enough common structure that the novel control flow doesn't doesn't surprise people using the monad. Common ways to do this are by composing monad transformers, returning special value types, or using continuations.
That said, you get more flexibility to define data flow in Haskell if you combine the ordinary monadic parts with data flow libraries like pipes/conduit/machines. But you're still free to not return anything from a function (or technically a monadic action) in Haskell, as long as you're in a monad where returning nothing is a possibility.
This is certainly a problem with first-order programming, where we might have function signatures like:
foo : A -> B
bar : B -> C
baz : C -> D
And we plumb them together into: quux : A -> D
quux x = baz (bar (foo x))
IIUC the problem you're describing is that a change causes one of these functions, say `bar`, to gain an error condition. We can represent that by: bar' : B -> Maybe C
Our `quux` definition would then become: quux' : A -> Maybe D
quux' x = case bar' (foo x) of
Nothing -> Nothing
Just y -> Just (baz y)
I don't think it's too bad to have a failing function return a special value like `Nothing` to indicate that: `return Nothing` is no more difficult than `throw SomeException`, `exit 1`, etc. The problem is having everything in-between the error and its handler having to propagate it, like above. This sort of 'check if successful, return Nothing if not' (anti-)pattern seems to crop up a lot with e.g. Java programmers being introduced to `Optional`. It seems like we're going to drown in null checks (or Nothing checks, in this case).Yet this problem isn't so bad if we use higher-order programming (functions of functions, etc.). In particular, we can write the first `quux` as a higher-order combination of those other functions (where `f ∘ g` is composition of `f` and `g`, i.e. a function which applies `g` to its argument, then applies `f` to that):
(f ∘ g) x = f (g x)
quux : A -> D
quux = baz ∘ bar ∘ foo
This ability to compose is really powerful. The FP community (taking their terminology from maths) call these composable things "categories", and functions are one example of a category; another is circuitry, where we can wire the output pins of one circuit to the input pins of another. In the context of this article, a (non-branching) railroad track is an example of a category (we can place one piece of track after another). There's a nice description of categories at http://www.haskellforall.com/2012/08/the-category-design-pat...Now what if we then need to propagate error conditions? We can just treat that error-propagating ('check if successful, and return Nothing if not') functionality as an alternative form of composition, which I'll write as `⋅`:
(f ⋅ g) x = case g x of
Nothing -> Nothing
Just y -> Just (f y)
quux' : A -> Maybe D
quux' = baz ⋅ bar ∘ foo
In fact we can be a little more general by defining a `map` function instead; this lets us do error-handling even if we only have a single function, and we can re-use the normal ∘ composition: map f x = case x of
Nothing -> Nothing
Just y -> f y
quux' : A -> Maybe D
quux' = map baz ∘ bar ∘ foo
This looks like the same amount of boilerplate as the first-order version, but operations like `map` are general enough that they'll probably be included in the language by default, or at least with the library that defines `Maybe`, `Just` and `Nothing`. Hence the only code we need to write to go from `quux` to `quux'` is `map`.Just like with composition, lots of things can be 'mapped'. FP calls such things "functors", although beware of other uses for that term (e.g. some languages use this phrase to mean function objects; some, like Ocaml, use it to refer to module transformers). Another example of a functor is lists, where `map` applies a function to all of a list's elements. In fact, if we think of lists as "containing any number of values" then we can think of `Maybe` as "containing at most one value". Going the other way, if we think of `Maybe` as being "a result which either failed or succeeded" then we can think of lists as being "a result which either failed or succeeded in any number of ways", i.e. lists are just non-deterministic computations (e.g. see Wadler's "How to Replace Failure by a List of Successes" https://rkrishnan.org/files/wadler-1985.pdf )
Another example of a functor is functions: a function `g : A -> B` can be thought of as 'containing' some `B` return values, which we can 'access' by providing an `A` value as input. If we have a function `f : B -> C` we can apply it to those return values by doing `map f g : A -> C`. We get a new function 'containing' `C` return values, which we can 'access' by providing an `A` value. How does such a function work? It just takes the `A` value that we give it, passes it into `g` to get a `B` return value, then passes that into `f` to get the final `C` return value. In other words, the `map` function for functions is just the `∘` composition operation!
Another example of a functor is an I/O action, for example reading a temperature sensor. I/O actions are like functions, in that they 'contain' return values (e.g. temperature readings), which can only be 'accessed' by executing the action (e.g. performing a measurement). Just like functions, we can `map` over these actions as a form of composition: if we have `a : IO Temperature` and `f : Temperature -> Either Hot Cold`, then we can do a form of composition using `map`, where `map f a : IO (Either Hot Cold)` is an action which can measure whether it's hot or cold (by executing `a` then feeding the result into `f`).
Another thing we might want to do is 'unwrap' nested values. For example if we have a possibly-failing function `g : A -> Maybe B` and a possibly-failing function `f : B -> Maybe C` then we can use `map f g : Maybe (Maybe C)`, which might be `Nothing` (if `g` failed), or it might be `Just Nothing` (if `g` succeeded but `f` failed) or it might be `Just (Just something)` (if both succeeded). If we don't care about which one failed, we can use a function called `join : Maybe (Maybe A) -> Maybe A` to replace `Just Nothing` with `Nothing` and `Just (Just something)` with `Just something`.
FP people call joinable things "monads", and in the case of `Maybe` we can think of it as concatenating together a list-of-at-most-one-(lists-of-at-most-one-element) to get a list-of-at-most-one-element; or as turning a combination of error cases into a single error case. For lists, we can think of `join` as concatenating lists-of-lists; or as turning chains-of-successful-results into successful-results. For functions we can think of `join` as making a function which re-uses its argument for the subsequent step. For I/O we can think of `join` as turning an action-which-measures-which-action-to-take-next into an action-which-measures-then-does-something.
In most other languages you either don't know if an exception could be thrown or you just assume every function throws one. Then when you are adding in things like promises which explicitly define success and failure paths the system must implicitly catch all exceptions and pass them to your error path...unless the developer chooses to change that functionality.
Much nicer to have all that defined for you in the type system, even though it existed without it.
Personally, I'm not entirely convinced, though. In practice, exceptions will still occur unless the language doesn't have them, so now you have two mechanisms to deal with errors. (.NET has a strong culture of exceptions—no thank you to lots of wrappers to make established libraries use result types.) Also, it doesn't seem realistic to anticipate every possible error scenario. Sometimes all you know is that something went wrong. That's fine. Show a generic error and improve the software once the cause has been identified. Still, I would like there to be a better way to find out about the most common exceptions than reading documentation.
When using Either in that way, I tend to think of it as a structured exception. It gives you a defined exit point, just like in other structured programming. I've tried to introduce this on our team and probably there is about 50/50 acceptance. Half of the people think it is awesome, half of the people can't see the point, so I think it's probably an acquired taste.
In railway pattern, we return values to callers, which then call the next function in turn.
(All that said, if you're thinking in terms of multiple inputs and outputs you're missing the point. The output isn't a pair, it's one or the other, and that's really important. You need to be able to make invalid states unrepresentable, so a disjoint union is not just a pair)
"Building a backtracking facility in smalltalk without kernel support"[1]
Languages like Snobol, Prolog, and Icon were designed with backtracking facilities from the outset and these facilities are deeply intertwined with the implementation. Retrofitting a backtracking facility in a language that wasn't designed for it has never been achieved. We report on an experiment to retrofit Smalltalk with a backtracking facility. The facility is provided through a small number of primitives written in the language (no modifications to the kernel were made). The ability to do this is a direct result of the power provided by the objectification of contexts.
There's tons of other examples, for example various distributed objects mechanisms, my own Higher Order Messaging [2] the way Gemstone creates queries from procedural selection code etc.
https://tahoe-lafs.org/~davidsarah/noether-friam4.pdf has a more concrete set of tradeoffs: starting from a small, highly symmetric core, you add more capabilities to the language but you break a symmetry each time. One of the levels in the rainbow is an OOP language, but that requires breaking enough symmetries that I wouldn't want to work in it if I could avoid it.
Yes. Yes. We know. You can write programs with OO. It's the dominant paradigm of the software industry. No one here saidthat OO is somehow ineffective, cannot abstract, or lacks cleverness.
Please for even comment section just put down the sword and let other folks with equally interesting approaches talk about their work.
Only in the example showed in the website, if you want to have progress reports/feedback on your happy path and keep it even if you go to the error path then having a multiple result/structure containing both results at the same time make sense.
Also, We're not taking about maybe types here. This article is demonstrating a specific library that composes a specific either type using F#'s computation expressions or custom operators.
Lots of people don't know what computation expressions are, nor are they familiar with the bind operator. They don't know why they'd use an either type instead of try/catch.
You can always reduce the number of words to say something, but you often sacrifice context and end up alienating people when you take too much for granted.
You also know what type the error will be. No need to derive a new class from `Error` and add custom functions to extract the data from your failure case, just pass the data along.
It's not about avoiding the goto like behavior. It's about making you to know it exists and forcing you to handle it.
Rathet than throwing 5 calls deep, doing nothing until you empty your call stack, you must explicitly say "I know I'm part of a system that may error" at each step along the way.
I've been writing a lot of Kotlin recently, and Kotlin doesn't have checked exceptions. This has led me to start migrating away from exceptions entirely because without checked exceptions it gets too hard to track what can fail, and how. I've been switching to an approach like the author's of using an `Either` (actually `Validated` from arrow-kt -- a special purpose `Either`) to have failures in my return values. I just have to be careful when calling library code to immediately translate exceptions into return values, but the entire stack in my own code has no exceptions (aside from unrecoverable errors).
That said, it's often preferred to use Either<Success,Error> because then you can try to explain what went wrong. A Maybe cascade failing can be pretty mysterious when you start to compose them, and you're deliberately creating something your optimizer will inline into an difficult-to-debug straight line of code.
It's basicall what Angular 2 should have been.
On the other hand, callbags seems to go a step further and could be simplify things even more.
public abstract class Maybe<T>
{
public abstract T Value { get; }
public virtual string Failure => null;
public SelectMany<U, V>(Func<T, Maybe<U>> f, Func<T, U, V> g)
{
var that = f(this.Value);
if(that.Failure != null)
return new Failed(that.Failure);
return new Success(g(this.Value, that.Value));
}
public sealed class Success : Maybe<T>
{
public override Value { get; }
public Success(T value) => this.Value = value;
}
public sealed class Failed : Maybe<T>
{
public override Failure { get; }
public override Value => throw new InvalidOperationException();
public Failed(string s) => this.Failure = s;
}
}
Maybe<string> UpdateCustomerWithErrorHandling()
{
return
from req in receiveRequest();
from v in validateRequest(req)
from c in canicalizeEmail(req)
from d in db.updateDbFromRequest(req)
from e in smptServer.sendEmail(req.Email)
select "OK";
}Valid C#: https://gist.github.com/noblethrasher/2d0e99f86b9853c646f3fa...
Second, you're trapping and propagating successful values in a monad, which means your obligating the caller to handle both success and error conditions.
How large, and why? Only when exceptions are thrown, or also during the happy path?
From what I understand, with Monads the code check errors after each expression (like in C/Go), but behind the scene. Isn't it the case? If so, wouldn't that incur an overhead that is not present with exceptions, where normal code runs without checks and where "throws" perform a sophisticated jump?
This is where I want to make a key distinction between exceptions and errors ala Railway programming. Performance with exceptions doesn't really matter because exceptions are supposed to be exceptional.
With Railway oriented programmer, the whole point is that you're encoding errors into the logic of some type of system. These types of errors may not only be not exceptional, they may a very regular part of the application.
Like I told another commenter, a friend of mine uses them in an application where they easily would throw thousands of exceptions per second if they used exceptions. Not only would it undermine the performance of their system, it's using the wrong tool for the job.
It shouldn't matter much anyway: You usually don't optimize for exceptional cases, especially if they lead to program termination.
And furthermore, you should not make heavy use of exceptions anyway :-). They lead to non-local control flow that is extremely hard to follow. They are nice for short scripts where they print a stack trace and abort the program. But they are a huge maintenance burden in larger programs.
Railway oriented programming is better suited when errors are much more common in the ringtone and when their handling is a fundamental part of the rules you're encoding.
One friend uses a Railway oriented approach precisely because throwing that many exceptions per second (I don't know the exact number) would severely undermine the performance of their system.
Developers are better off in the end with proper exceptions because these sorts of Result objects don't scale. Haskell ultimately embraces proper exceptions and I suspect Rust will get there too eventually. F# actually has proper exceptions which makes you wonder why the author is reinventing the wheel badly.
Mechanism used by CPython (and IIRC many C++ implementations) involves having per-thread flag "exception occurred" which is checked after every function return (this makes sense performance-wise when essentially every function contains "implicit try/finally" in form of bunch of Py_DECREF or destructors of locally scoped variables).
The same idea can be implemented by returning instances of special "ExceptionThrown" class and checking for that, which you in fact can do by doing "if argument is ExceptionThrown return argument" in prologue of every function, which is exactly the thing described in the article. (early versions of dfsch did exactly this)
Only when you know that in most cases you don't need to do significant cleanup on stack-unwind (ie. you have tracing GC that directly scans stack or you don't allocate that much) it starts to make sense to do stack unwinding by doing non-local jumps.
Typical implementation of that has some linked-list of currently active try/catch/finally sites that has to be maintained at runtime (typically as part of activation records on control stack). Extension of this idea is that such sites do not necessarilly have to unwind-stack before running the recovery code (i.e. Windows' SEH). And then that you can have two such lists, one for handling errors and other for cleanup during stack unwind (i.e. CL-style condition system)
In this scenario, performance matters because you want the creation of the error (these aren't exceptions) to be relatively cheap because it is a regular part of the system.
In these scenarios, using exceptions would be abusing exceptions, because exceptions are typically supposed to be exceptional.
The amount of boxing and unboxing as you go through the various switches actually can ultimately make this much less efficient than the exception based flow. The code was ultimately something like 8 times as slow, and topped out CPU on beastly boxes which was surprising to me.
Please don't entertain these silly posts. At best, it only grants legitimacy to a crassly presented idea.
In most cases, I'm not interested in the types of exception that can be thrown. And when I need the type of an exception, a runtime check suffices in almost all cases.
Let's not make exception handling more cumbersome than it needs to be, and only invoke verbose mechanisms when necessary.
Because then you lose the ability to have code that doesn't error. If you explicitly mark those parts of your code that can error, you can then start to decouple those parts that can error from those that will never error. E.g. you can separate the business logic which figures out which database query you need to run (which can't error) from the code that actually performs database queries (which contains timeouts, retry logic etc.), and then you can test those two things separately and make sure you've covered all the cases. Whereas with pervasive/implicit exceptions, every line of your business logic might throw an exception (or might not throw an exception now, but later be refactored to throw one), so you need to test a combinatorial number of cases (or, more likely, your tests won't cover some code paths).
It's also increasingly popular in languages with less exclusively academic DNA. Swift's community is considering adopting a moral equivalent. Rust uses a very Haskell-ish variant. Golang uses a related variety cribbed from Common Lisp called "product-type errors" (as opposed to "sum-type errors" used here).
If this is a fad, then so is Python, Golang, and Java.
But, people absolutely use MVB in cases where an ADT would work. Especially in FFIs where CL's restarts would make the underlying bindings way more complex or underperform. I can go find some examples when I'm off hours, if you like.
Here [0] is an example of how I've used this technique in functional JavaScript code. Please don't judge too hard as this was my first JS library 2+ years ago... certainly lots of problems in there (although it has been running untouched in production since then!)
[0] https://github.com/milesrichardson/kewt.js/blob/master/kewt....
For example:
No, I don't need a "cartoon intro to DNS over HTTP" to understand basic networking concepts. Nor do I need a story about "Dr Frankenfunctor and the Monadster" to understand functional programming concepts. Even when I was a teenager reading about OOP, I didn't want to read about the "Car class inheriting from the Vehicle class" or the "Dog class inheriting from the Animal class."
When reading technical content, I always prefer prose that treats its readers as professionals, rather than five-year-olds incapable of understanding complexity without resorting to vacuous and incomplete analogies. The problem is that complex topics are complex. By their very nature they rarely fit into convoluted analogies, and would be better explained by simple use cases and examples.
I cannot see the reason for featuring javascript in this context.
A promise would be the case in an async functions but railway like presented work in sync functions.
Promises also sorta recursively build up and tear down (IIRC) while railway is a "pass along" situation; each function that generates and error calls the next function with the error where you then simply pass it along (or handle it).
Not sure what you mean by "recursively build up and tear down" but this JS snippet sure looks a lot like the F# one in the slides
const updateCustomerWithErrorHandling = (...args) =>
receiveRequest(...args)
.then(validateRequest)
.then(canonicalizeEmail)
.then(updateDbFromRequest)
.then(sendEmail)
.then(handleSuccess, handleError)
Here, each of the functions can return a result (async or not) or reject with Promise.reject or by throwing. If any of the functions rejects, the rest of the functions in this "happy path" are not called.Consider code like this:
p1
.then((value) => {
console.log(value);
return Promise.reject('oh, no!');
})
.catch((e) => {
console.log(e);
// Handle the error if you want, and keep going
return Promise.resolve()
})
.then(() => {
console.log('This still gets executed')
})
How is this not amenable to the railway pattern? You define how you handle the error within a function in the promise chain. Error handlers are fully composable with success handlers, which seems to be the important element necessary for implementing the railway pattern.Rxjs streams are monads because you can map a stream to a stream which wraps the inner stream in a source stream, which you can then flatMap.
The railway oriented approach is then looking at neat ways of working with these kind of results in the place of try/catch when dealing with errors.