45
Railway Oriented Programming
(fsharpforfunandprofit.com)
Welcome to the main community in programming.dev! Feel free to post anything relating to programming here!
Cross posting is strongly encouraged in the instance. If you feel your post or another person's post makes sense in another community cross post into it.
Hope you enjoy the instance!
Rules
Follow the wormhole through a path of communities !webdev@programming.dev
Any suggestions on how this could be implemented in Python?
Why not just throw an error?
Catch it higher up the chain, and return that as the response.
Which would essentially the "early return" methodology. The final return of a function is the happy path, everything else is tested for and thrown as an error before hand (or returns a different value depending on the structure).
I don't know why further parts in a chain (or "2 track railway") of methods would want to process an error.
Like, why not just have the error instantly return to the client.
Maybe, for things like input validation, having a list of errors would be useful (IE email is invalid, passwords don't match, password must be 8 characters, and accept TOS).
Even then, that is a validation step. The main chain of processing shouldn't care if there is 1 or 5 errors. Validation doesn't pass, return the validation error.
The only reason I can see is if you have some response handler that can accept an error or data, and you don't want to write a try/except, or you don't want to abstract the try/except to some parent method, or you find that try/excepts have some critical performance penalty that is wholey unacceptable.
I feel like this 9 year old solution is looking for a problem, or is an example of working within strange constraints, or is just an idea/example for a specific talk.
Maybe it's just being purely functional for the sakw of being functional?
Idk. Maybe I just don't get functional programming?
Typically the error track of the railroads analogy is implemented as a short circuit/return, so in effect this behavior IS an early return, but elegantly masked as though you are just handling the happy path.
In rust, if you function returns a Result type (the Either type from the slides), you can track a ? On to the end of any function call that returns a Result. This gets de-sugared to a check for an error and returns from the function early if it is.
At that point, the caller of the function gets to choose if they want to handle the potential failure of your function, or just let it bubble up further by using the ? operator. You end up with the behavior you’re describing, but with the benefit of errors handled by the type system and code that looks cleaner by just (explicitly) handling the happy path.