What Is Referential Transparency?

From SitePoint
March 15, 2017 - 1:00pm
In functional programming, referential transparency is generally defined as the fact that an expression, in a program, may be replaced by its value (or anything having the same value) without changing the result of the program. This implies that methods should always return the same value for a given argument, without having any other effect. This functional programming concept also applies to imperative programming, though, and can help you make your code clearer. To understand this article you should know how to write simple classes and methods in Java. Knowing what a side effect is helps but if you don't, you'll learn it on the way. Referential Transparency The expression referential transparency is used in various domains, such as mathematics, logic, linguistics, philosophy and programming. It has quite different meanings in each of these domain. Here, we will deal only with computer programs, although we will show analogy with maths (simple maths, don't worry). Note, however, that computer scientists do not agree on the meaning of referential transparency in programming. What we will look at is referential transparency as it is used by functional programmers. Referential Transparency in Maths In maths, referential transparency is the property of expressions that can be replaced by other expressions having the same value without changing the result in any way. Consider the following example: x = 2 + (3 * 4) We may replace the subexpression (3 * 4) with any other expression having the same value without changing the result (the value of x). The most evident expression to use, is of course 12: x = 2 + 12 Any other expression having the value 12 (maybe (5 + 7)) could be used without changing the result. As a consequence, the subexpression (3 * 4) is referentially transparent. We may also replace the expression 2 + 12 by another expression having the same value without changing the value of x, so it is referentially transparent too: x = 14 You can easily see the benefit of referential transparency: It allows reasoning. Without it, we could not resolve any expression without considering some other elements. Continue reading \%What Is Referential Transparency?\%

Continue reading this article »