Tip 34: Focused Parameters with Partially Applied Functions

In this tip, you’ll learn to keep parameters focused with partially applied functions.

In the last tip, you saw how you can easily create higher-order functions with arrow functions. If you come from an object-oriented background or just haven’t seen much code that uses higher-order functions, you may have problems understanding when you should use higher-order functions.

Partially applied functions provide unique value by locking in parameters so you can complete the function later while still maintaining access to the original arguments. They also isolate parameters so you can keep intentions clear. In the next tip, you’ll see more about locking in parameter data. In this tip, you’ll see how you leverage higher-order functions to give parameters single responsibility.

Partially applied functions & focused parameters

A higher-order function is a function that returns another function. What this means is that you have at least two rounds of parameters before the function is fully resolved. With a partially applied function, you pass some parameters and you get back a function that locks those parameters in place while taking more parameters. In other words, a partially applied function reduces the total number of arguments for a function—also called the “arity”— while giving you another function that needs a few more arguments.

The takeaway is that you can have multiple sets of parameters that are independent of one another. Perhaps it seems like parameters already have single responsibility. They are, after all, the input data to the function so they must relate to one another. That’s true, but even inputs have different relationships. Some inputs are related to one another while others are more independent.

Think about an events page on a website. An event is going to occur in a specific space. Each event is unique, but the space isn’t going to change radically between events. The address, name, building hours, and so on will be the same. In addition, spaces are managed by people who are points of contact, and they will seldom change between events.

With that in mind, consider a function that needs to combine information about the space, the space manager, and an event on a page. You’ll likely get each piece of information from a different source, and you’ll need to combine them together to return the complete information.

Example

Here’s a sample of the data you’ll receive.

  • The building has an address and hours.

  • The manager has a name and phone number.

Then you have two different event types.

  • The first, a program, will have a specific hour range that’s shorter than the building hours.

  • The second, an exhibit, will be open as long as the building is open but will need the curator as a contact.

Get hands-on with 1200+ tech skills courses.