0

So, I believe I understand pure functions. Something similar to abs or sqrt where the output is dependant on input and has no side effects. However I am confused about how this works with methods.

If we view a method as a function with an implicit this parameter, then I would assume that a method such as the one below would indeed be pure.

class Foo
{
    int x;

    [Pure] public int Bar() { return x * 2; }
}

Is it a correct assumption that the function is pure? Would it make a difference if the read variable was readonly/const?

Programmdude
  • 551
  • 5
  • 22
  • If the caller cannot accurately predict the result then its not pure. So this is not pure. So why would the caller use it? Because it may be a complex operation and the caller does not want to implement it. In other words the result has to be deduced only from the input and nothing else. – CodingYoshi Sep 15 '17 at 03:19
  • Why is this tagged c++? – Passer By Sep 15 '17 at 03:24
  • @passerby Because it is language agnostic. So it could be tagged anything. But ya why is it: pehaps the user wants an example in those languages – CodingYoshi Sep 15 '17 at 03:27
  • Not to be confused with c++ **pure** _virtual_ methods. https://stackoverflow.com/questions/1306778/c-virtual-pure-virtual-explained –  Sep 15 '17 at 03:37
  • Pretty much because these are the two languages I use where pure and objects come into contact with each other. – Programmdude Sep 15 '17 at 07:05

1 Answers1

1

A function is considered pure when:

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...

From Wikipedia

Bar isn't pure because it depends on the variable x. So the result of Bar() would be different on different occasions if the value of x changes.

Imagine something like this:

var obj = new Foo();
obj.x = 1;
obj.Bar(); // Returns 2.
obj.x = 5;
obj.Bar(); // Returns 10.

Whereas, if x were a constant/readonly, it would still be pure because, the results of Bar() would never change.

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
  • I like to add that if you cannot, for comprehension purpose, replace your method call by the value it's supposed to return and have your program run the same, then said method isn't pure as well. – Kilazur Sep 15 '17 at 08:17