Referential Transparency: Why Can an Expression Be Replaced Without Changing the Result?

Referential Transparency: Why Can an Expression Be Replaced Without Changing the Result?

Referential transparency does not mean that code is easy to read. It is a rule of substitution: an expression can be replaced by its value without changing the rest of a program's behaviour. Every occurrence of 2 + 3 can be replaced by 5. Reading the current time cannot be treated this way, because its result depends on when it is evaluated.

This matters because it lets us break a whole-system problem into local ones. Inputs and the expression are enough to reason about the output; hidden state, external files and execution order need not be tracked at the same time. Testing, caching and parallel recomposition therefore become more dependable.

Referential transparency is close to determinism, but the two are not identical. An operation may return the same result every time while also changing external state; replacing it with the result would then erase an effect. Immutability often helps achieve referential transparency, but is not the rule itself. The central point is that referential transparency protects a reasoning boundary: a local substitution must not disturb the whole.


Discover more from Geoffrey Chen

Subscribe to get the latest posts sent to your email.