In this tutorial, you will learn what currying is and how you can use it in order to make your code cleaner. Currying is a key part of functional programming. The main aim of functional programming is to favour writing small, well-defined functions.
What Is Currying?
Currying is the process of converting a function that takes multiple arguments and converting it into a function that takes one argument at a time. When I first read about currying, I didn't really see the benefit. Most of the beginner tutorials are pretty short and simple, instead of writing this:
You write this:
If that doesn't impress you, then welcome to my world. The benefit of currying isn't really in the definition, but the code you use to call that function. In the normal function definition code, you would call the function like this:
In the curried function you would call the function, like this:
In the hurried approach, I pass the first variable 10 to add as the first parameter and assign it to a new variable, add10. After add10 is defined, I can omit passing 10 to add ever again, as I can now simply use add10. This approach adheres to the DRY principle, as it is eliminating unneeded duplication in your code, which is a software design approach you want to ensure your code follows?
If you only need to apply add10 once, then currying can be a bit of an overkill. Your code can become easier to understand as your code can be written in a more declarative style, e.g. add10 has a more descriptive name, than simple seeing lots of add(10,5), add(10,10) dotted around your codebase.
For a more real-world problem, let's say you have a web form and you have a helper function that creates field inputs for you, like a textbox. The website works in 20 different languages, each field needs to have different regions, validation and error messages depending on the user's location. I could end up with lots of code like this:
You can also do it in less code using currying like:
If you have 20 odd fields in your form, the second approach while contains more set-up code will eventually use less code than the first approach.
The main benefit of currying is when you need to use the same call with some of the same parameters a lot. In these situations, currying becomes a good technique to use. Curring will make your code easier to refactor. Currying also creates a more declarative code base, e.g. it's easier to read the code and understand what it's doing - if your code is written well that is!
Currying is not a set in stone coding style to use all the time technique. Currying is useful in certain situations. When you need to use the same function calls a lot, currying is a pretty easy concept to apply to your code. Chain your function arguments into multiple single calls, rather than passing multiples arguments at the same time.