DEV Community

Discussion on: Explain Pure Functions Like I'm Five

Collapse
 
kspeakman profile image
Kasey Speakman

My two general rules to ensure a pure function.

  1. Output depends only on input parameters
  2. No mutation of external state (including passed-in parameters)

Notes for impure languages (languages which allow mutation and other side effects from user code).

  • I'm a little lenient with #1 in cases where it is obvious the external data will never change as long as the program is running. E.g. constants, or readonly data read from a config on startup. The latter is still better as an input parameter.

  • One common way new devs violate #1 is to get the current date/time or generate a random number. You want to do this outside your pure function and pass the result in so the function remains pure (and testable).

  • The #2 allows a function to mutate a local variable and remain pure. As long as the variable is only created/used inside the function, the function still has no side effects that ripple to the outside.