20.1. Create Methods with No Side Effects (Pure Functions)
In keeping with the best practices of Functional Programming (FP), you want to write “pure functions.”
In general, when writing a function (or method), your goal should be to write it as a pure function. This raises the question, “What is a pure function?” Before we tackle that question we need to look at another term, referential transparency, because it’s part of the description of a pure function.
If you like algebra, you’ll like referential transparency. An expression is referentially transparent (RT) if it can be replaced by its resulting value without changing the behavior of the program. This must be true regardless of where the expression is used in the program.
For instance, assume that
y are immutable variables
within some scope of an application, and within that scope they’re
used to form this expression:
You can assign this expression to a third variable, like this:
Now, throughout the given scope of your program, anywhere the
x + y is used, it can be
z without affecting the
result of the program.
Note that although I stated that
are immutable variables, they can also be the result of RT functions.
"world".length will always be
10. This result could be assigned to
z, and then
z could be used everywhere instead of this
Although this is a simple example, this is referential transparency ...