Functional Programming – Function with Same Input and Side Effects

functional programmingpure-functionside-effect

Say we have a normal pure function such as

function add(a, b) {
  return a + b
}

And then we alter it such that it has a side effect

function add(a, b) {
  writeToDatabase(Math.random())
  return a + b;
}

It's not considered a pure function as far as I know because I often hear people call pure functions "functions without side effects." However, it does behave like a pure function as far as the fact that it will return the same output for the same inputs.

Is there a different name for this type of function, is it unnamed, or is it still actually pure and I'm mistaken about the definition of purity?

Best Answer

I'm not sure about universal definitions of purity, but from the point of view of Haskell (a language where programmers tend to care about things such as purity and referential transparency), only the first of your functions is "pure". The second version of add isn't pure. So in answer to your question, I'd call it "impure" ;)

According to this definition, a pure function is a function that:

  1. Only depends on its input. That is, given the same input, it will always return the same output.
  2. Is referentially transparent: the function can be freely replaced by its value and the "behavior" of the program will not change.

With this definition, it's clear your second function cannot be considered pure, since it breaks rule 2. That is, the following two programs are NOT equivalent:

function f(a, b) { 
    return add(a, b) + add(a, b);
}

and

function g(a, b) {
    c = add(a, b);
    return c + c;
}

This is because even though both functions will return the same value, function f will write to the database twice but g will write once! It's very likely that writes to the database are part of the observable behavior of your program, in which case I've shown your second version of add isn't "pure".

If writes to the database aren't an observable part of your program's behavior, then both versions of add can be considered equivalent and pure. But I can't think of a scenario where writing to the database doesn't matter. Even logging matters!