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
2
u/saintpetejackboy Dec 30 '23
I want to jump in here a bit and say:
FP versus OOP comes down to more about how you think to solve a problem and how your mind handles getting from point A to point B. Obviously you see the same results using FP or OOP, so it more comes down to personal flavor and preferences.
Many people end up mixing and blending both types of logic, so it can be useful to have a grasp on both to some extent, as you may end up needing to have some kind of interaction in your code that is easier to handle with a OOP versus FP.
Personally, I prefer to be entirely procedural. It makes sense, in my mind. When I think about a problem I see the data and the code and they manifest in sequence. That isn't true for everybody, some people are super awesome at objects and see the components of the problem materialize.
Cognitive Differences between programming paradigms