Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
roth_stephan_clean_c20_sustainable_software_development_patt.pdf
Скачиваний:
29
Добавлен:
27.03.2023
Размер:
7.26 Mб
Скачать

Chapter 7 Functional Programming

What Is Functional Programming?

It is difficult to find a generally accepted definition of functional programming (sometimes abbreviated FP). Often, one reads that functional programming is a programming style in which the whole program is built exclusively from pure functions. This immediately raises the question: what is meant by “pure functions” in this context? We will address this question in the following section. This definition is basically correct: the foundations of functional programming are functions in their mathematical sense. Programs are built by a composition of functions, and the evaluation of functions and function chains.

Just like object orientation (see Chapter 6), functional programming is a programming paradigm. That means that it is a way of thinking about software construction. However, the functional programming paradigm is also often defined by all those positive properties attributed to it. These properties, which are regarded as advantageous compared to other programming paradigms, especially object orientation, are the following:

•\ No side effects by avoiding a (globally) shared mutable state. In pure functional programming, a function call does not have any side effect. This important property of pure functions is discussed in detail in the following section, “What Is a Function?”

•\ Immutable data and objects. In pure functional programming, all data is immutable, that is, once a data structure has been created it can never be changed. Instead, if we apply a function to a data structure, a new data structure is created as a result that is either

a new one, or a variant of the old one. As a pleasant consequence, immutable data has the great advantage of being thread-safe.

•\ Function composition and higher-order functions. In functional programming, functions can be treated like data. You can store a function in a variable. You can pass a function as an argument to other functions. Functions can be returned as results from other functions. Functions can be easily chained. In other words, functions are first-class citizens of the language.

295

Chapter 7 Functional Programming

•\ Better and easier parallelization. Concurrency is basically difficult. A software designer must pay attention to a lot of things in a multithreaded environment that she usually does not have to worry about when there is only one single thread of execution. And finding bugs in such a program can be very painful. But if calls of functions never have any side effects, if there are no global states, and if we deal solely with immutable data structures, it is much easier to make a piece of software parallelizable. Instead, with imperative languages, like object-oriented ones, you need locking and synchronization mechanisms to protect data from being simultaneously accessed and manipulated by several threads (see the section entitled “The Power of Immutability” in Chapter 9 on how to create an immutable class object in C++).

•\ Easy to test. If pure functions have all the positive properties mentioned here, they are also very easy to test. It is not necessary to consider global mutable states or other side effects in test cases.

We will see that programming in a functional style in C++ cannot fully ensure all of these positive aspects automatically. For instance, if we need an immutable data type, we have to design it in a way I’ll explain in Chapter 9. But now let’s dive deeper into this topic and discuss the central question: what is a function in functional programming?

What Is a Function?

In software development, we can find many things that are named “function.” For instance, some of the features that a software application offers its users are often also called the program’s functions. In C++, the methods of a class are sometimes called member functions. The subroutines of a computer program are generally considered functions. No doubt, these examples are also “functions” in the broadest sense, but not the functions that we deal with in functional programming.

When we talk about functions in functional programming, we are talking about true mathematical functions. That means that we consider a function as a relation between a set of input parameters and a set of permissible output parameters, whereby each set of input parameters is related to exactly one set of output parameters. Boiled down to a simple and general formula, a function is an expression like this: y=f(x).

296

Chapter 7 Functional Programming

This simple formula defines the basic pattern of any function. It expresses that the value of y depends on, and solely on, the value of x. And another important point is that for the same values of x, the value of y is always the same! In other words, the function f maps any possible value of x to exactly one unique value of y. In mathematics and computer programming, this is known as referential transparency.

REFERENTIAL TRANSPARENCY

An essential advantage that is often mentioned in conjunction with functional programming is that pure functions are always referentially transparent.

The term referential transparency has its origins in analytical philosophy, which is an umbrella term for certain philosophical movements that have evolved since the beginning of the 20th Century. Analytical philosophy is based on a tradition that initially operated mainly with ideal languages (formal logics) or by analyzing the everyday language of everyday use. The term “referential transparency” is ascribed to the American philosopher and logician Willard Van Orman Quine (1908 – 2000).

If a function is referentially transparent, it means that anytime we call the function with the same input values, we will always receive the same output. In other words, we are theoretically able to substitute the function call directly with its resultant value, and this

change will not have any impact. This enables us to chain together functions as if they were opaque boxes.

Referential transparency leads us directly to the concept of the pure function.

Pure vs Impure Functions

Listing 7-1 shows a simple example of a pure function in C++.

Listing 7-1.  A Simple Example of a Pure Function in C++

[[nodiscard]] double square(const double value) noexcept { return value * value;

};

297

Chapter 7 Functional Programming

As it can easily be seen, the output value of square() depends solely on the argument value that is passed to the function, so calling square() twice with the same parameter value will produce the same result each time. We have no side effects, because if any call of this function is completed, it does not leave any “dirt” behind that can influence subsequent calls of square(). Such functions, which are completely independent of an outside state without side effects, and which will produce the same output for the same inputs and are referentially transparent are called pure functions.

In contrast, imperative programming paradigms, such as procedural or object-­ oriented programming, do not provide this guarantee of side-effect freeness, as the example in Listing 7-2 shows.

Listing 7-2.  An Example Demonstrating That Member Functions of Classes Can Cause Side Effects

#include <iostream>

class Clazz { public:

int functionWithSideEffect(const int value) noexcept { return value * value + someKindOfMutualState++;

}

private:

int someKindOfMutualState { 0 };

};

int main() {

Clazz instanceOfClazz { };

std::cout << instanceOfClazz.functionWithSideEffect(3) << std::endl; // Output: "9"

std::cout << instanceOfClazz.functionWithSideEffect(3) << std::endl; // Output: "10"

std::cout << instanceOfClazz.functionWithSideEffect(3) << std::endl; // Output: "11"

return 0;

}

298