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...
An expression is called referentially transparent if it can be replaced with its corresponding value (and vice-versa) without changing the program's behavior. This requires that the expression be pure – its value must be the same for the same inputs and its evaluation must have no side effects.
Referential transparency, a term commonly used in functional programming, means that given a function and an input value, you will always receive the same output. That is to say there is no external state used in the function.
An expression in a program is said to be referentially transparent if it can be replaced with its value and the resulting behavior is the same as before the change. This means that the program's behavior is not changed whether the input used is a reference or an actual value that the reference is pointing to.
From HaskellWiki. Referential transparency is an oft-touted property of (pure) functional languages, which makes it easier to reason about the behavior of programs.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With