Can a "pure" function reference a property?

256 views Asked by At

A pure function is one which given the same arguments, will always return the same result and will have no side effects.

So Sum(x,y) => x + y; is pure because it meets this criteria.

However, in a language like C# where you can have properties, this makes things more complicated...

class Summer
{
  public int X { get; set; }
  public int Y { get; set; }

  public int Sum() => X + Y;
}

In the above, can Sum be considered to be pure? Can you make the argument that X and Y are still just parameters to the function?

Or would it be better if refactored to something like:

class Summer
{
  public int X { get; set; }
  public int Y { get; set; }
}
static class SummerExn
{
  public static int Sum(this Summer s)
  {
    return s.X + s.Y;
  }
}

In the extension method, s is a parameter so this meets the criteria for being pure I think, but realistically there is no practical difference since the underlying variables are the same. Would there be a technical reason this code is better, such as being more easily tested, faster, more memory efficient, easier to logically reason about etc. ?

1

There are 1 answers

2
Tech Inquisitor On

Your example doesn't meet the definition you gave:

A pure function is one which given the same arguments, will always return the same result...

Every call is given the same arguments (none) yet obviously can return different results. Another definition from Wikipedia makes this a little more explicit:

The function return values are identical for identical arguments (no variation with local static variables, non-local variables...)

Properties are non-local variables.

And to be especially pedantic, not only is your example not a pure function, it's not a function at all. A function-like thing that's a non-static class member is called a method.