concept functional code in category functional programming

appears as: functional code, functional code
Functional Programming in JavaScript

This is an excerpt from Manning's book Functional Programming in JavaScript.

Although I don’t plan to apply equational reasoning to every program in the book, it’s important to understand that this is implicit in any purely functional program, and that it wouldn’t be possible if functions had side effects. In chapter 6, I come back to the importance of this principle in the context of unit testing functional code. Defining all function arguments up front avoids side effects in most cases, as with scalar values; but when objects are passed by reference, you must be cautious not to inadvertently mutate them.

In this chapter, we’ll look at why functional code is by definition inherently testable, whereas in most other paradigms, you must intentionally design your code to make it easy to test. Most of the best practices associated with proper testing—eliminating external dependencies, making functions predictable, and others—are core principles embedded in functional design. Pure, referentially transparent functions have this quality built into them for free and lend themselves to a more advanced method such as property-based testing. Before we begin, let’s take a moment to understand the influence FP has on the different types of tests and focus on where it will help you be the most productive: unit tests.

In contrast, the functional program handles the null case much more gracefully, because it only skips logic that would manipulate the invalid input (now null) directly. But the entire structure of the program (the interaction among functions) stays put and is successfully invoked and tested from start to finish. Recall that because there’s an error, the output of the functional code is a Nothing. You don’t have to check for a null output—the following test case is sufficient: