In this blog
R stands for Ramda.js. More on this later.
Here is code without R.
Code with R.
Is the refactored code better ?
What is R? What’s invoker? What’s pipe?
Good questions. Who could be against writing code that is easier to understand.
If all I’m writing is a function called
isUnique then of course the “before version” is simpler.
function is part of a bigger thousands of lines of code software.
A big software is nothing but a collection of smaller pieces of code. We compose code together to make code work.
We need to optimize for composability and as we write code that is more composable, we are finding that composable code is also easier to read.
Let’s take a look at another examples.
We have a list of users with name and status.
We need to find all active users. Here is a version without R.
Here is code with R.
Now let’s say that user data changes and we have a user with an empty name. We don’t want to include such users. Now data looks like this.
Here is modified code without R.
Here is modified code with R.
Notice that change we needed to do to accommodate this request.
In the none R version, we had to get into the gut of the function and add logic. In the with R version we added new function and we just composed this new function with old function using pipe. We did not change the existing function.
Now let’s say that we don’t want all the users but just the first two users.
We know what need to change in the without R version. In the with R version
all we need to do is add
R.take(2) and no existing function changes at all.
Here is the final code.
Data comes at the end
Another thing to notice is that in the R version nowhere we have said that
we are acting on the users. All the functions have no mention of
Infact all the functions do not take any argument explicitly since the functions are curried.
When we want result then we are passing
as the argument but it could be
articles and our code will still hold.
This is pointfree programming. We do not need to know about “pointfree” since this comes naturally when write with R.
I’m still not convinced that Ramda.js is solving any real problem
If you are still not convinced then, the author of Ramda.js has written a series of blogs called Thinking in Ramda. Please read the blogs. Slowly.
Functional programming is another way of thinking about the code. When we move to Elm, Haskell or Elixir to get functional concepts then we are wrestling with two things at once - a new language and functional concepts.