Subscribe to PHP Freaks RSS

Byte-sized functional programming: Pure functions make testing easy

syndicated from planet-php.net on July 14, 2020

Byte-sized functional programming: Pure functions make testing easy

When testing stateful code, you have to first set up all of the explicit and implicit state that a given piece of code depends on. If the object you're testing has many dependencies that could be complex, or references global variables, or calls many other routines with their own dependencies, you may be looking at a lot of complex setup that makes testing hard to do effectively.

Pure functions greatly reduce that problem.

A pure function is a function that:

  • has no inputs other than those explicitly specified;
  • has no effect on any value other than the value it returns.

That means there is, by definition, only one place to inject dependencies: the call itself. And there's only one effect to validate: the return value of the function. No need to call a function and check what the effect was on some other value or piece of code: by definition, the only effect is the return value.

If one of the parameters you pass in is itself complex, that may make the test complex. But if the parameter is complex, that can serve as an impetus to simplify it. Rather than passing in an object, for example, just pass in a single function. If that function in practice has more complexity behind it, fine, but it makes passing a mock function trivial. Just... make a new (anonymous) function for the one test.

When your code has fewer sneaky interactions, there's less effort involved in testing as well as fewer things to test.

---

Want to know more about functional programming and PHP? Read the whole book on the topic: Thinking Functionally in PHP.


Thinking Functionally in PHP
Larry 14 July 2020 - 9:28am