Tuesday, 16 September 2014

State in Functional Programming and OO

Just some musing...

In OO the global state, present in the old procedural programming, is broken up and the shards are moved into small, independent moving parts of the system, the objects. The objects don't expose their state, instead they expose behaviour. So the state disappears and and intricate net of acting agents fill its place. I have, like OO-fans, always seen this as an advantage, fascinated by the elegance of the transformation itself. But the disadvantage became obvious when I started learning FP. Since the state is obfuscated behind the objects' APIs, for a developer it can be hard to determine in exactly what state the system is. When I call a method on an object to return something it might send a message to another object or write into the DB and I won't know about it. Debugging is hard. Again I'm not sure it's a bad thing and I suppose sometimes it's good, e.g. in the case of logging. FP goes against this information hiding paradigm and promotes side-effect-free programming. Of course a program should have side-effects, otherwise what's the point? But FP forces the programmer to be very explicit about side-effects (= state changes). In an ideal FP architecture the inside of the onion is composed of pure functions and all the "impure stuff", like DB-operations, user input reading, web-service calling, etc, are in the outer layer, very visible, very explicit. So paradoxically, FB, being a state-shunning paradigm, is much more about the state than OO, which is about behaviour.

When I have some time and feel the creativity to do it, I'll append some examples.

No comments :

Post a Comment