3

Can a pure function use a private constant variable inside the same class?

for example:

class TimesThousand {
  const CONSTANT = 1000;

  function calculate(number) {
    return number * CONSTANT;
  }
}

can calculate() be considered as a pure function?

bbnn
  • 3,505
  • 10
  • 50
  • 68
  • 3
    What language is this? And yes, as written, that's a pure function. – melpomene Sep 14 '16 at 19:13
  • thank you for your answer. Just a draft rough code – bbnn Sep 14 '16 at 19:13
  • 1
    What do you think how would constants affect the purity of a function? Maybe don't call it "purity" but rather "[referentially transparent](https://en.wikipedia.org/wiki/Referential_transparency_(computer_science))" – Bergi Sep 14 '16 at 21:30

1 Answers1

5

A pure function is pure, when the return value is only determined by its input values, without any observable side effects.

So your function is pure. Since the value of CONSTANT is (as the name suggests) constant, the output is purely determined by the input.

From Wikipedia:

a function may be considered a pure function if both of the following statements about the function hold:

  1. The function always evaluates the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change while program execution proceeds or between different executions of the program, nor can it depend on any external input from I/O devices.
  2. Evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices.
Community
  • 1
  • 1
Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57
  • But the first statement does not hold since in two "different executions of the program", CONSTANT may hold a different value. For example APP_NAME is a constant, but may change depending on which instance of the program is running. Am i missing something? – P0lska Jan 25 '18 at 10:56
  • 1
    How would the value of `CONSTANT` ever change? It's an immutable value, meaning it can never change. – Luka Jacobowitz Jan 25 '18 at 13:51
  • 1
    @p0lska the only way for the constant to change is for the sourcecode to change, and the two instances are running two different versions of the app. If the two instances run the same version of the app then there is no way for them to return different values. – Wix Jun 07 '18 at 12:18
  • Well if you change the source code I'd argue it's a different function which is also pure for the same reasoning. We can't expect functions to be pure after changing the code for it – Luka Jacobowitz Jan 11 '21 at 15:34