官术网_书友最值得收藏!

Introducing functional programming

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:

"Object-oriented programming makes code understandable by encapsulating moving parts. Functional programming makes code understandable by minimizing moving parts."

                                                                                                                                                      – 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.

主站蜘蛛池模板: 盐池县| 马鞍山市| 宣化县| 宁海县| 广灵县| 湛江市| 拜城县| 江山市| 枝江市| 富平县| 方山县| 湖州市| 科技| 瑞金市| 南充市| 大竹县| 威宁| 溧阳市| 六盘水市| 贵南县| 阜康市| 五峰| 台南县| 南皮县| 万荣县| 隆尧县| 乐都县| 黄浦区| 离岛区| 卢龙县| 灵台县| 九龙坡区| 宁远县| 宣武区| 滦平县| 合山市| 克山县| 乐东| 日照市| 尉犁县| 望江县|