Pure methods in c++/c# classes

470 views Asked by At

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?

1

There are 1 answers

1
Nisarg Shah On BEST ANSWER

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.