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

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.

主站蜘蛛池模板: 万山特区| 长阳| 罗定市| 深泽县| 镇康县| 桑植县| 林州市| 临猗县| 报价| 江永县| 成安县| 永德县| 林口县| 涟源市| 柳林县| 梓潼县| 海原县| 彰武县| 阿拉善右旗| 宁河县| 河南省| 图片| 北辰区| 翼城县| 从化市| 新化县| 泸西县| 永兴县| 鱼台县| 开江县| 尼木县| 光山县| 黄山市| 丰都县| 德州市| 休宁县| 鄯善县| 邢台县| 德庆县| 武城县| 馆陶县|