Improving Control Flow with Higher Order Functions

Guong Le
SSENSE-TECH
Published in
3 min readSep 12, 2019
Image Source

In most programming languages there are two fundamental ways to manage control flow: loops and conditions. Regardless of whether your code is written in JavaScript, PHP, or Python, loops and conditional statements control the flow of logic and are the fundamentals of programming.

While loops and conditional statements can be easy to read and understand, in many cases, they fall short both in terms of code complexity and concurrency optimization as your software starts to scale. After following Adam Wathan’s Refactoring to Collections course, based on his guidance, I started to refactor some of my previous code. This process yielded results, most notably in simplifying my code and improving its comprehensibility. While I did not entirely ditch loops and conditions, I did end up replacing them as much as I could with techniques that I will introduce in this article.

My takeaways from Wathan’s course can be summarized as follows:

  • Whenever possible, use map and reduce functions to transform arrays without temporary variables.
  • When you need to get a subset of an array, use filters rather than loops and conditions.

Map, filter, and reduce are a subset of functions known as ‘higher order functions’ (see next section for details). They are key elements of the functional programming paradigm and offer a way to run transformations on an iterable data structure concurrently. Mastering the use of map, filter, and reduce techniques yields great results over time. Also, it is arguably the most important concept to understand when working with big data:

  • While the naming conventions might differ, this paradigm can be applied in most languages: array_map(PHP) vs .map(JavaScript) for example.
  • By reducing the amount of code you need you write, it can greatly improve your code’s readability. Code with reduced cyclical complexity is easier to understand, review, and explain.
  • Map, filter, and reduce functions can usually fully exploit your infrastructure’s concurrent processing capabilities, unlike traditional loops and conditional statements which must be executed linearly.

Higher Order functions

A higher order function takes one or more functions as arguments, and returns a function as its result. All other functions are first-order functions. Higher order functions like map, filter, and reduce can effectively create a separate layer of abstraction for all control flow code. I recommend that every programmer add these to their toolkit and learn when to reach for them.

Example of First Order Functions
Examples of Higher Order Functions

Map

PHP

array_map ( callable $callback , array $array1 [, array $… ] ) : array

JavaScript

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
// Return element for new_array
}[, thisArg])

Python

map(function_to_apply, list_of_inputs)

A map function simply maps every element in an iterable data structure (like an array) to a unary function and returns the results in the same order as the iterable data, achieving the same result as a `for`, `while` loop, but with more elegant design and potentially limitless room for concurrency. This function should be every developer’s default option for array/collections transformations.

Reduce

PHP

array_reduce(array, myfunction, initial)

JavaScript

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

Python

reduce(function, sequence[, initial]) -> value

Like the map and filter functions, the reduce() function receives two arguments, a function, and an array. However, rather than returning another array, it returns a single value. Its key utility is to operate within the array by starting from an initial value, performing an operation with the subsequent value, and carrying the result to “reduce” the collection to a single value. Let us see how this works in practice…

With a classic for loop:

With array_reduce:

There are two advantages of using a reduce array function as seen above:

  1. No temporary $sum variable
  2. The function can be unit tested

Conclusion

While loops and conditional statements undoubtedly have their place in the world of programming, higher order functions for control flow management have proven themselves to be a wonderful idea. Entire distributed data processing frameworks such as Apache Spark and Hadoop MapReduce have been built atop these fundamental concepts. Using map, filter, and reduce will also introduce you to key ideas of the functional programming paradigm such as idempotence, pure functions, and immutability. Exposure to such concepts will improve the quality of software you design and broaden your mind as a programmer.

Editorial reviews by Deanna Chow, Liela Touré & Prateek Sanyal.

Want to work with us? Click here to see all open positions at SSENSE!

--

--