13 ms·
Railway-Oriented Programming (2015)
- jgtrosh 8y agoI think that this uses a very specific model which can be represented with railroads, but also any other 1-way system. For example, you could say it's like hanging from a glider where you travel in a happy path, or can fall down at any point and keep travelling on foot on a failure path. This analogy is not much better but I feel like there's a better analogy out there than railroads.
- lmm 8y agoWhat railroads evoke is that there's a very limited number of paths you can take. A glider calls to mind just the opposite - complete freedom in where you fly to.
- m_mueller 8y agoIMO the railway analogy works well, because it describes the right dimensionality. It's sort of a 1.5D problem with a directed graph, with a chain of events plus a fallback chain. A railway captures that perfectly while giving people a clear picture they can understand, assuming they imagine a train that can only move in one direction and decides its path based on switches on the track. With something like a glider you could ask questions like "but what if it flies off to the East" or "what about vertical air movements that carry it up or down" and so on...
- jgtrosh 8y agoI agree that's a problem with the glider image, but that's the issue I had with railroads as well—there's much more freedom than what is shown here; railroads can go multiple ways, join in various orders etc. What I mean is one line change in a given direction does not imply subsequent ones will be in the same.
- meddlepal 8y agoThis feels like a lot of words and fp "stuff" to describe a system where a function takes two inputs (anyval0, maybe<error>) and ouputs (anyval1, maybe<error>) and you chain them together.
- deleted 8y ago[deleted]
- meowzero 8y agoNo, it's a system that takes 1 input (anyval0) and outputs either an error OR anyval1. If any of the functions errors, it rides the "error" track back up and returns the first error that it encounters. This is fail fast method using flatmap.
- woah 8y agoSounds like it’s a convoluted way to implement the same kind of thing that you’d get with a traditional error throwing paradigm
- hderms 8y agoWhat's convoluted about it? Exceptions jumping up multiple stacks and being rescued or reraised or what have you is convoluted. If you mean errors as return values then I agree, monads are more complicated than returning a simple error type.
- jecxjo 8y agoThe part you might be missing is that you're explicitly told "this function returns a value OR and error. You must handle error cases with this function". With the try/catch paradigm you never know from the function definition if that is the case. 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.
- steego 8y agoSome people don't understand what it means to chain functions returning maybe types together, so they need more words. 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.
- fortythirteen 8y agoSo... try/catch?
- fredley 8y agoYes, but in a functional paradigm.
- amelius 8y agoI'm wondering: why not make every returned value implicitly of type Either with Left some generic type? 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.
- beojan 8y agoNot all functions can produce an error. If you add two arbitrary precision integers, you're not getting an error.
- amelius 8y agoSo (+) would be defined as adding its operands, except if one of them is an error (in which case the result would be an error).
- jjaredsimpson 8y agoEither is a sum type. What if I don't want that. It's not about handling errors per se, but modeling the type.
- amelius 8y agoYes, I understand. But by "implicitly" I really meant that. You don't see the type, only the compiler does. The programmer only sees the non-error part of the type (the "Right" part of Either).
- PLenz 8y agoAnd here I was hoping this was about CMRI/JMRI
- ant6n 8y agoAnd here I was thinking this was about ERTMS/ETCS
- chatmasta 8y agoI'm surprised there's not a single mention of JavaScript promises in the post. This is basically what they are, and their syntax naturally imposes this technique as a solution to most use-cases. 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.js#L326 https://github.com/milesrichardson/kewt.js/blob/master/kewt....
- zaarn 8y agoIt's not quite a Promise. 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).
- chatmasta 8y agoNot sure what you mean by "build up and tear down" but in what way do promises not pass errors to the next function in the chain? 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.
- joshribakoff 8y agoPromises are functors not monads because they map (.then) but the return value becomes the new promise. The chain is flat 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.
- erk__ 8y agoOld discussion: https://news.ycombinator.com/item?id=11955917 https://news.ycombinator.com/item?id=11955917
- cup-of-tea 8y agoNice to see somebody else use a railway analogy. I like to use railways to describe why interfaces and encapsulation are important engineering principles. The track gauge is the interface between the people that build the railway and the people that build the trains. As long as they both implement the interface then together they get something much greater than the sum of its parts.
- xenomachina 8y agoAnother place a railway analogy is used in CS is railroad diagrams for representing context-free grammars: https://en.wikipedia.org/wiki/Syntax_diagram https://en.wikipedia.org/wiki/Syntax_diagram
- erikb 8y agoI either haven't gotten the point or have to assume there isn't one. Isn't that normal error handling? The incoming error path is usually even done with exception handling in normal languages, so you don't have to worry about it. the pattern `if not <assertion>: raise Exception` should be everything one needs. And for that this whole stuff is really fancy and long, especially if one considers that most people (sadly) don't even check assertions between function calls, if they are not forced to by bug reports.
- mpweiher 8y agoWhat I found interesting is that if you have a pipe/filter architectural style, your happy path stays completely free of error handling, because when a filter doesn't have a good result, it just doesn't pass any data to the next filter in line. Done! 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.
- klodolph 8y agoThis pattern isn't as complex as it looks, it's just the same pattern as you've always used with some mathematical terms added to it. Having a "stderr"-like output on a filter can also be expressed as a Monad. Instead of Either or Maybe, or in general error monads, you could use a writer monad like WriterT. (Haskell, not sure about F#.) 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.
- mpweiher 8y ago> just the same pattern as you've always used 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.
- stingraycharles 8y agoThrowing exceptions can be considered a (very) poor man’s Monad, so I suspect this is the pattern they’re talking about.
- klodolph 8y ago> What's the "pattern I've always used"? 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.
- hliyan 8y agoIt is time someone wrote an essay arguing for non-oriented programming (NOP?) and requirements driven development (RDD?). In my darker moments, I tend to see some of these trends in the same light as certain diet fads...
- KirinDave 8y agoThis style of programming has existed for about as long as Python has, and has seen substantial improvements both in classical environments (ML & Haskell) and experimental environments (Idris and Agda). 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.
- junke 8y agoCommon Lisp multiple values are not used for error handling as far as idiomatic code is concerned. The also work differently, being symetrical to optional parameters.
- KirinDave 8y agoIt's not common, but it's doable and Golang copied the approach for its error handling, which is what I was referring to more directly. 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.
- deleted 8y ago[deleted]
- protomyth 8y agoOn the same train of thought, there was a book called "Plug and Play Programming: An Object-Oriented Construction Kit by William Wong" that detailed a similar concept in C++. Its an old, hard to get book, but did a nice job of it.
- DenisM 8y agoWay I could do this in C#. Tried doing something like this myself, but it didn’t work out.
- noblethrasher 8y agoHere is a moral equivalent in C#: 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"; }
- noblethrasher 8y agoActually, the above code doesn't compile (I just dashed it off while waiting for a real world project to compile). Valid C#: https://gist.github.com/noblethrasher/2d0e99f86b9853c646f3fa91c59b2223 https://gist.github.com/noblethrasher/2d0e99f86b9853c646f3fa...
- DenisM 8y agoIs that the same concept here: https://ericlippert.com/2013/04/02/monads-part-twelve/ https://ericlippert.com/2013/04/02/monads-part-twelve/
- Melchizedek 8y agoI would recommend this library https://github.com/louthy/language-ext https://github.com/louthy/language-ext for functional style programming in C#.
- Animats 8y agoOver 100 PowerPoint slides, which don't even play if you have tracking blocked.
- k__ 8y agoI like the way Cycle.js follows this principle. 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.
- develop7 8y agoA healthy person's lungs^W Rails.