My understanding is that the term "referential transparency" can really only be applied to functional code. However, a method call on an object in object-oriented code can have a similar property, which is that the return value of the method, and the state of the object after a method call depends only on the state of the object before the call, and the method's arguments.
i.e. functional referential transparency:
i = foo(n, m);
// return value depends only on n, m
OO "referential transparency":
i = obj.foo(n, m);
// return value, and subsequent state of obj, depends
// only on initial state of obj, n, m
Is there a name for this property?
If the state of obj
does not change during the call to foo()
, then the "object oriented" style is equivalent to the functional form if function overloading is supported since it could be rewritten as:
i = foo(obj, n, m);
// return value depends only on obj, n, m
However, is pretty common for the state of obj
to change in a method call, so I'm not sure if this helps the analysis...
Your mistake is thinking that FP and OO are somehow fundamentally different. The "OO version" of referential transparency is just referential transparency.
An expression e
is referentially transparent if and only if e
can be replaced with its evaluated result without affecting the behavior of the program.
So if you have an expression o.foo(a)
, then it is referentially transparent if you could modify your code to replace it with the result of the call, without changing how your program behaves. Obviously, if o.foo is void, you can't do that. Ditto if it modifies the internal state of o
. So the only way for o.foo(a)
to be referentially transparent is if its result is a function of o
and a
.
In my mind, "functional code", is synonymous with "referentially transparent code".