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.
View all comments
Show parent comment
9
u/phlummox Dec 26 '23
Sure, and I'm telling you not to think of it that way. There's no "under the hood"! If you're working in a statically typed language, the left and right types are out in the open - nothing is hidden!
Also, often the left-hand type - your error type - will be much more "fixed" ; for instance, it might always be a string. And the right hand type is often more likely to vary with the "layer" you're in. (This isn't a rule, or anything, just something that often tends to be true.)
So rather than think of Either as "two types" (which of course, it isn't), it's more useful to think of it as an enrichment of the right-hand type.