+ 2

About pure functions

Lately I read a description about what 'pure' actually means: The function may have no contact whatsoever with the outside world except via args and return value. That means, it can't even print or generate a random number, because that means interaction with the operating system. Other functions it may call - but only if these are pure themselves. Now my questions: 1.) How pure do the 'purists' here write their functions in real life? How often or in which cases do you choose to write purely or not? 2.) And what about imports of modules or libraries, is that considered the 'outside world' too?

2nd Sep 2018, 7:24 PM
HonFu
HonFu - avatar
2 Respostas
+ 6
I try to code as "purely" as possible. This means for example that I try to have all my I/O code in one place. That's useful because I can easily feed in other data by rewriting I/O but the logic stays the same. Sometimes I will model time explicitly, so my main code stays pure by not using Date.now(). This is useful because I can rerum experiments or slow time down, without changing the pure codebase. In languages that allow it, I will at least make the seed of a PRNG configurable. I try to keep as little state as possible, that means cut down on variables that influence functions from afar. I pass in everything as a parameter; by seperating logic and state like that, I can again easily switch out the data. Pure code is great because you don't have to worry about anything when using it. You can multithread pure code trivially (no I/O -> no deadlocks), and you can memoize them, that means store the results of a function in a lookup table to speed it up.
3rd Sep 2018, 4:02 AM
Schindlabua
Schindlabua - avatar
+ 1
Pure functions are a concept that is related (not exclusively) to functional programming. They are useful because you can trust they won't do unexpected things, so can lead to more safe and maintainable code. However it's not a requirement (in fact I think it is impossible) to have your entire codebase be pure, nor is it necessary. It's useful for unit tests too, because if a function doesn't only depend on its parameters and doesn't give the same result for each run, how can you test it? If it has side effects then it might be difficult to test all of those and can be difficult to track down bugs
3rd Sep 2018, 7:22 AM
Dan Walker
Dan Walker - avatar