r/functionalprogramming • u/jfmengels • Sep 21 '24
Question Non-obvious benefits of pure code
Like probably a lot of you, I really like writing code without side-effects (at least as much as possible), because it has plenty of benefits, such as easier to predict and to maintain, etc.
What are some benefits of writing code in a pure way (completely or partially) that are not obvious to newcomers or - even better - to more experienced programmers?
21
Upvotes
19
u/legobmw99 Sep 21 '24
By far the coolest one that has stuck in my memory is how the abstractions common to purity can lead to interesting alternative algorithms for problems, like described in https://blog.jle.im/entry/shuffling-things-up.html
12
u/nrnrnr Sep 21 '24
Pure code is so, so, so much easier to test. Especially if the language of your choice has QuickCheck or some other tool for property-based testing.
10
u/a3th3rus Sep 21 '24
Immutability also brings us perfect thread safety (or in general, concurrency safety), because there are only shared values that can't be changed, and no shared states.
3
u/Slight_Art_6121 Sep 22 '24
As I commented on the same question on r/AskProgramming : code becomes more readable so code comments can be focused on the “why” instead of the “what” and “how”
4
u/lilyallenaftercrack Sep 21 '24
For me, a great benefit right now is that is much easier to make LLMs get things right with pure code. If I need help with something, the only context it needs is the actual snippet
1
u/[deleted] Sep 22 '24
I'm not completely sure why, but I really connect with the names.
sumis just what you get when you take in numbers and add them up. It doesn't care what they're for or where they came from or even what they're called. The function is calledsumand that's what matters.When I saw
foldI instantly knew what it was about, despite seeing that kind of thing before and getting caught up in the details.1
u/Inconstant_Moo Sep 22 '24
It makes it easy (automatable) to factor out part of a function as being a subexpression. You can say, extract everywhere it says
x * xand replace that with a local variable calledxSquared, and this will work because x is immutable.Or you can extract out a part of a function (any part which doesn't cut a block in two) and say, make this its own function called
foo, and it can figure out what parameters and local variables it needs, again because the variables are immutable.In my own language one advantage from the values being immutable is that you can use microservices as though they were libraries, they're a namespace where you can call the public functions and this Just Works. But it wouldn't work if the values were mutable (or would become kinda nightmarish) because what happens if you pass a mutable value to a microservice and then six weeks later it needs to get back to the caller and say "hey, remember that mutable value from six weeks back? I mutated it."