Functional programming (FP) is a programming paradigm that receives its name from the way we build applications when we use it. In a programming paradigm such as OOP, the main building blocks that we use to create an application are objects (objects are declared using classes). However, in FP, we use functions as the main building block in our applications.
Each new programming paradigm introduces a series of concepts and ideas associated with it. Some of these concepts are universal and are also of interest while learning a different programming paradigm. In OOP, we have concepts such as inheritance, encapsulation, and polymorphism. In functional programming, concepts include higher-order functions, function partial application, immutability, and referential transparency. We are going to examine some of these concepts in this chapter.
Michael Feathers, the author of the SOLID acronym and many other well-known software engineering principles, once wrote the following:
– Michael Feathers
The preceding quote mentions moving parts. We should understand these moving parts as state changes (also known as state mutations). In OOP, we use encapsulation to prevent objects from being aware of the state mutations of other objects. In functional programming, we try to avoid dealing with state mutations instead of encapsulating them.
FP reduces the number of places in which state changes take place within an application and tries to move these places into the boundaries of the application to try to keep the application's core stateless.
A mutable state is bad because it makes the behavior of our code harder to predict. Take the following function, for example:
function isIndexPage() {
return window.location.pathname === "/";
}
The preceding code snippet declared a function named isIndexPage. This function can be used to check whether the current page is the root page in a web application based on the current path.
The path is some data that changes all the time, so we can consider it a piece of state. If we try to predict the result of invoking the isIndexPage, we will need to know the current state. The problem is that we could wrongly assume that the state has not changed since the last known state. We can solve this problem by transforming the preceding function into what is known in FP as a pure function, as we will learn in the following section.