In functional programming, pure functions are at the core of this paradigm. When we speak of pure functions we mean that these functions satisfy two main conditions; the first is that they will not cause any side effects and the second is that depending on their arguments they will return the same result. When you create pure functions you should try to make them take care of one thing and only one, so your functions will be very easy to test and scale. Consider the following function:
message = 'Ruby is awesome'
def transform text
text.upcase!
end
transform message
print message
## => RUBY IS AWESOME
This function is impure because it modifies its argument called
message
. Bang (!) methods often contain side effects, which means they will mutate the state. In order to make this function pure and don't modify its state, we could use the next approach.message = 'Ruby is awesome'
def transform text
text.upcase
end
transform message
print message
## => Ruby is awesome
How you can see is simple to achieve a pure approach avoiding the bang (!) method but pure functions are not only avoiding the bang method they are a set to make code more readable and testable.
It sounds a little difficult to understand but in this article, I will make it easier for you to clear all your doubts. We'll start by talking about main concepts like Side Effects and Referential Transparency and with those main concepts you could build pure functions.
When you hear about Referential Transparency that means that an expression can be replaced by its result. Let's say you have a basic arithmetic operation that is,
20 + 12
so you easily could replace it by 32
, without changing the behavior of your program. You can extend the definition also to functions. So you can say +
is referentially transparent, because if you call it with the same values, it will give you the same answer.Side effects are changes in the state, or some interaction with outside elements (the user, a web service, another computer, whatever) that occurs during the execution of some calculations. We have different side effects we could find but the most popular ones are:
The concept of Functional Programming is not only for the Ruby Programming Language, you could use this Programming Paradigm in languages such as JavaScript, Python, Scala. etc.
If you would like to get deep with Ruby in general, I really recommend you to read this book, there is a chapter where you could find more information about Functional Programming: The Well-Grounded Rubyist 3rd Edición