Skip to content

Instantly share code, notes, and snippets.

@myknbani
Created April 26, 2022 03:04
Show Gist options
  • Save myknbani/d5d66142fc6127a4e941d3e0ea024e70 to your computer and use it in GitHub Desktop.
Save myknbani/d5d66142fc6127a4e941d3e0ea024e70 to your computer and use it in GitHub Desktop.

Benefits of pure functions

  1. Easier to reason about

    • a pure function tells everything you need to know about the function. No hidden I/O, no external variables modified, no instance or even global variables to hunt down.
  2. Easier to test

    • since the same input(s) always return the same output(s), they're easy to test. Provide the input and expected output. Simple! No need for setup, teardown, or mocking.
    expect(last([3, 9, 5])).toBe(5) // that's it!
  3. Easier to debug

    • Debugging is like detective work, and there are less suspects to investigate, since you don't have to worry about mutations, side-effects, and variables outside the pure function.
  4. Easier to combine

    • Pure functions can act like LEGO blocks, when used with function composition or piping.
  5. Easier to parallelize

    • Since pure functions don't modify any of its parameters or any outside variables, you can be sure they're thread-safe. The OS can run these functions using any number of cores and in any order.
  6. Easier to cache

    • Some functions are expensive to calculate, e.g. the permutations of abcde. The results of a pure function can be cached, and calling permutation('abcde') the second time will be faster, since the result will be retrieved from the 🐇cache rather than 🐢recomputed.
  7. and many other benefits

    • Referential transparency, laziness, idempotency,... It even makes it easy for bundlers to tree-shake frontend code that's composed of pure functions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment