DEV Community

John Kazer
John Kazer

Posted on • Updated on

Functional programming is great, but not for the reasons everyone keeps telling you

There is no necessarily fundamental reason why functional programming is better than a procedural or object oriented approach. Yes, pure functions, clean code, readability etc. may make your programmes safer and easier to reason about.

But that isn't why I like functional programming.

I simply prefer the way it allows me to think about problem solving. Maybe the world is inherently split into programmers who think functionally and those who think procedurally - someone should fund a psychology research project!

As an example, say I have some data structure and would like to transform it. My thought process is to start writing down a list of actions that I think will be needed. This is an iterative process, as the consequences of each action becomes clearer and extra steps are added. I might also realise that a particular action is really a special case of something that already exists - so I just co-opt that action (or function). In doing so, I may have to change it to make it more generic - but that's fine because it's a pure function and therefore safe.

After a while, I might write some pseudo code which simply sets out the logical action sequence - often the initial list of actions is the pseudo code. And this pseudo code often ends up being the actual function I want. Then there is a detail which is the additional implementation needed to flesh-out some of the functions implied by specific actions in the pseudo code.

If there is iteration needed, that's a single recursive function which can be defined in pseudo code by name at this stage. It is sufficient to know that an iteration is needed and what form the output will take.

If there is a sequence of actions needed, that's a composition which the pseudo code represents with a sequence of functions.

If the logic determines that data needs transforming (e.g. filtering) then that's fine, just state it as an action. The result will be used further down the pseudo code and no need to worry about side-effects because there are none.

So the logical steps to get from initial data to result are quickly clear and little additional infrastructure is needed to just make it happen. This to me is how many people already solve problems and therefore functional programming doesn't necessarily need any change of mindset.

However, the wrinkle is that the incremental state of the data is not immediately obvious - the functional approach almost wants you to not care. And therefore your real mindset switch is to one of imagining data structure transformations as the chain of functions progresses.

Top comments (0)