Pankaj Patil
2 min readJul 6, 2022

--

A working definition of pure function

A pure function can be defined like this:
The output of a pure function depends only on
(a) its input parameters and
(b) its internal algorithm.

This is unlike an OOP method, which can depend on other fields in the same class as the method.

A pure function has no side effects, meaning that it does not read anything from the outside world or write anything to the outside world.

It does not read from a file, web service, UI, or database, and does not write anything either.

As a result of those first two statements, if a pure function is called with an input parameter x an infinite number of times, it will always return the same result y.

For instance, any time a “string length” function is called with the string “Pankaj”, the result will always be 6.

As a few examples, Java and Scala functions like these are pure functions: String uppercase and lowercase methods
List methods like max, min
Math.sin(a), Math.cos(a)

In fact, because the Java String class and Scala List class are both immutable, all of their methods act just like pure functions.

Even complex algorithms like checksums, encodings, and encryption algorithms follow these principles: given the same inputs an infinite number of times, they always return the same result.

  1. Conversely, functions like these are not pure functions:
    System.currentTimeMillis
  2. Random class methods like next, nextInt
  3. I/O methods in classes like File and HttpURLConnection that read and write data

The first two examples yield different results almost every time they are called, and I/O functions are impure because they have side effects — they communicate with the outside world to send and receive data.

--

--

Pankaj Patil

Software Engineer | Blogger | Reader | Writer| Political and Social Activist