
Joseph Fuge
Published: 07-26-2025
Pure Functions
Are your functions pure?
If you don’t know what that means, then they’re probably not.
What is a pure function?
Simply put, a pure function is a function with no side effects.
Just like allergy medicine whose commercials state that “common side-effects may include…” as rapid after-thoughts muttered faster than your elementary school teacher expected you back from the bathroom, a function with side effects can keep you up at night later down the road.
What are side effects?
In this context, side effects are non-deterministic inputs; the same input can give me a different output each time.
Common side effects may include:
- Accessing the filesystem (file system could change between function calls)
- Making network calls (you send a request and wait for a response, which could be different every time)
- Accessing global variables (global variables could be changed by other pieces of code)
- Accessing the current time (the current time is always changing)
- Using a random number generator (result will always be different)
Pure functions should be easy to understand and as deterministic as possible.
For example, if I have a function that reads data from a CSV file, performs operations on the data, and then returns the result, I run the risk of different results every time I call the function.
If I separate the function into: One function which reads a file and returns the data called readCSVInput(filePath) Another function that converts the data into a usable format called convertCSVTextToArray(csvText) And a third that performs operations on the data and returns the results called calculateData(data), the outcome brings a myriad of benefits.
- I get consistent results every time I call the “convertCSVContentToArray” or the “calculateData” function with the same parameters
- Automated tests / unit tests are easier to write and rely on - I can test each function individually
- The function can be re-used more easily in another part of the code
- The code likely becomes more readable - I can understand 3 small functions better than 1 large function
Ask your doctor if impure functions are right for you.
Take care