Pure Functions
Functions that always return the same output for the same input and produce no side effects.
Also known as: Pure Function, Referentially Transparent Function
Category: Software Development
Tags: functional-programming, software-engineering, testing, programming
Explanation
A pure function is a function that satisfies two conditions: it is deterministic (always returns the same result given the same arguments), and it has no side effects (does not modify any state outside its scope or interact with the outside world). Pure functions are a cornerstone of functional programming.
Benefits of pure functions include: predictability (easy to reason about behavior), testability (no setup or teardown needed, just input and expected output), parallelization (can be safely executed concurrently since they don't share mutable state), memoization (results can be cached since same inputs always produce same outputs), and referential transparency (function calls can be replaced with their return values).
Examples of pure functions: mathematical operations (add, multiply), string manipulation (concat, substring), data transformations (map, filter, reduce). Examples of impure functions: those that read/write files, make network requests, access current time, modify global variables, or generate random numbers.
In practice, most programs need some impure operations (I/O, persistence, user interaction). The functional programming approach is to push impure operations to the edges of the system while keeping the core logic pure. This 'functional core, imperative shell' pattern combines the benefits of pure functions with the necessity of real-world interactions.
Related Concepts
← Back to all concepts