r/functionalprogramming • u/ACrossingTroll • Dec 26 '23
Question Deeply nested exceptions
Hi, I'm currently learning FP and many concepts I see I have actually already implemented myself in OOP. One thing though is still a bit fuzzy to me, and that's error handling.
Let's say I want to parse some (string) and either it's valid and returns the parsed value (int) or it returns an error (string). As I understand it, with FP you would use EITHER, with the left (error) and right (happy) path. Afterwards you can nest the error path vs happy path with FLATMAP, effectively passing through the error, or continuing the program flow. So far so good, I hope.
Now my concern is: what if your error check happened 30 levels down the stack? Wouldn't that mean you constantly have to FLATMAP until you finally deal with the error on level 5 etc, like printing it? Also doesn't that mean you pretty much would end up flatmapping your functions all the time because error handling is everywhere? Like writing a "flatmappedfunction" you'd use all over the place?
This is where OOP seems to be much easier. I know it is obfuscating the program flow a bit. But you just would need to throw the exception once and deal at the appropriate place up in the stack. Instead of 30x FLATMAP?
Please correct me if I'm wrong.
25
u/eddiewould_nz Dec 26 '23
Might not answer your question, but functional programmers tend to prefer "parsing" over "validating".
That basically means instead of having a function that "checks" a value is valid (and returning/throwing an error if it isn't), the function will return a more specific, narrow type.
For example, a function that takes a string value and returns a EmailAddress type.
The remaining functions will only accept that narrow type (otherwise you get a compilation error). If the type is EmailAddress (instead of string) we don't need to check it's valid a second (or third) time.
Furthermore, functional programmers will tend to do this value parsing "early on" in the call stack/program (as early as possible!) so deeply nested errors generally shouldn't be a problem.
14
u/paul_schnapp Dec 26 '23
In my experience it's rare that I will have to messily propagate an error that far, for a few reasons:
flatmap(monad) chaining can be hidden behind a layer of abstraction called: workflows (F#), for-comprehensions (Scala), or do-notation (Haskell). That way, as u/minus-one notes, you can just deal with the happy path and leave the ugly chaining to the language's syntactic sugar.There are similar techniques such as applicative validation to help ease the burden of error-handling too.
It does take a bit of time to learn to think that way though, and for me at least it was difficult at first, but it's worth it imo.
3
u/See-Ro-E Dec 29 '23
In my opinion, exception handling in Object-Oriented Programming (OOP) style can be considered as a form of an incomplete Either Monad with syntax sugar. When using a language that lacks syntactic sugar for monads (like do-notation or for-comprehension), and you want to implement a robust system using the Either Type, you need to use explicit expressions like bind. However, in functional languages like F# or Scala, syntactic sugar or meta-programming techniques can hide more complex code.
In my case, I prefer not to use the Either Type with OOP, even if it includes FP (Functional Programming) features, in languages like TypeScript, Kotlin, Python, etc., that do not support first-party or syntactic sugar for this concept. This is because it feels unnatural and doesn't align with the language's philosophy. Similarly, I don't favor OOP-style reactive programming for the same reasons.
However, I enjoy using the Monad concept in languages that are natively designed for FP, like F#.
Nevertheless, this might not be the perfect answer for you as it is just a matter of personal preference
6
u/dominjaniec Dec 26 '23
maybe not direct answer, but the Railway Oriented Programming maight be an idea you are looking for: https://fsharpforfunandprofit.com/rop/ (from the great Scott Wlaschin)
2
u/minus-one Dec 26 '23
but you don’t need to flat map all the time, that’s exactly what monad is for. they allow you to deal only with the happy path (and with errors only when you need it)
4
u/aijan1 Dec 26 '23
I don't know what language you are using, but if you are trying to write 100% functional code, exceptions are obviously out of the question. I'm personally ok with 90% functional code as long as the remaining 10% mixed-paradigm code is separated clearly from the functional code.
1
u/miracleranger Dec 27 '23 edited Dec 27 '23
i'd like to understand the problem, and smart people seem to get you, but riddle me this: however you implement error handling, it is thrown somewhere along a stack trace, and caught anywhere higher along the stack trace. imperatively, you wrap a function call in a try/catch, objectorientedly you may abstract that into some dependency injection (or whatever have you, i rarely see justification for any OO abstraction), or functionally into a monadic combinator (either/maybe etc.). i write in javascript too, i have a combinator called "buffer", but i've seen more intuitive names for it like "trap", which creates a closure around a try/catch call to a given function (buffer(parse,error=>resolve(error)) - the error may be thrown wherever inside "parse". the same combinator is used internally in my "either" combinator to combime this further into repeated function application: either(parse,fallback,fallback), and so on. async support requires a little more work, but that's not strictly an error handling question). what cases of error handling get more complicated than this to raise any further design questions?
4
u/TheInnerLight87 Dec 26 '23 edited Dec 26 '23
I don't think it's helpful or accurate to think of error handling as a topic that can be neatly divided into FP/OOP approaches. It's perfectly acceptable, even good, practice to throw exceptions in pure functional code in the correct circumstances and also it's good practice to put the errors in the return value in imperative code in the correct circumstances too.
Those circumstances depend on the expectations of your program.
Those who are familiar with Haskell will be aware of the somewhat notorious
headfunction in the standard library that throws exceptions when it receives an empty list.This function has notoriety not because throwing exceptions in Haskell is a terrible idea but because exceptions are totally expected within the domain of that function. The exception is problematic because it takes a totally routine and expected event (receiving an empty list) and treats it as an exceptional circumstance.
On the other hand, it's totally fine to have a http call with type
IO arather thanIO (Either ... a). You can treat the unusual circumstances: failure to decode, server unreachable, timeout, etc. as exceptional if you feel that is most appropriate. Most of the time, you probably just want to log the error and move on.You quite rightly point out in your original post that madness lies in mapping layers and layers of exceptions types if you start trying to make all exceptions explicit. Doing so breaks abstractions, makes you write huge volumes of boilerplate or leads you to really bad practices like making errors
stringly typed.The precise boundaries of where you should draw that line is going to vary based on language community. Rust is going to heavily favour typed errors and Java is going to heavily favour exceptions but you can still
panicin Rust and you still have, for example, theOptionaltype in Java. The same fundamental principles apply, the decisions lie in the ambiguous parts in the middle and you'll need to be guided by the specific language community in those areas.In my personal experience, exceptions are the tool that I'd reach for first and only change if my business logic requires me to start doing some inspection of those error states. Like many functional programmers, I went through an idealistic phase trying to do the opposite 5-6 years ago and ultimately felt that I wasted far too much time writing boring and valueless error-mapping code that, 99% of the time, simply did not justify the effort.
TLDR: Use the right tool for the right job. If you're writing C++ and an error is totally expected within the domain of the function, put the information in the return value. If you're writing Haskell and something unexpected happens, value your time, throw an exception and move on with your life.
2
u/Sea_Estate6087 Jan 06 '24
Let's say you call a function f(...), and somewhere nested in the further calls of f, an exception is thrown when it is a full moon. Now, the function f is not pure. Sometimes f(x) returns y and sometimes (on the full moon) it does not. A primary goal of functional programming is to make use of pure functions. f(x) should *always* return y. Then the real world comes in, and sometimes there is an error. You can keep f pure, by instead of f "doing something", it "returns a thing that will later do something". It *always* returns exactly the same "thing that will later do something" when given x, and that thing, "at some later time", will either return y, or fail with an exception. At this point, f is pure again. This is what you want to strive for -- think about how to keep everything pure until the last possible moment. So, returning an either[error, y] is better than throwing an exception, because it always returns a value, but returning a "thing" that will resolve to [error, y] when "the outside world is involved" is even better, because now, f *always returns the exact same thing* regardless of the phase of the moon.
This is more than just a matter of style -- think of testing a program with state. You have to consider all possible states, and then, select some subset which you can then set up artificially, and "run the tests". But the more pure functions you have, the less state there is. Ideally, there would be absolutely zero state -- this is the easiest software to test, because if f(x) returns y in the test, and f is pure, there is absolutely *nothing* that could prevent y from being returned at runtime.
This is the kernel of the reason why you want to avoid exceptions, and move to always returning values, and then later, using monads and other techniques. The higher percentage of your code that is running "pure" (absolutely no communication with the outside world), the much easier it will be to verify the program and test the program and in the end, the more reliable the program.
1
u/Qnn_ Dec 26 '23
Its definitely a verbose writing style but it really shines when someone else is reading your code and instantly understands the control flow.