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. ?
Sum(), get 0. SetXto 1. CallSum()get 1. Called with the same arguments, got different results.Summerobject multiple times and come out with different results (ifSummerhas been mutated inbetween). Of course the exact same argument applies to the first method if you considerthisto be a hidden parameter. In other words: there is quite literally no difference and there cannot be, as long as you mix in references to mutable objects. You can have methods that will not modify state and so are easier to reason about, but that's not the same thing.