The Benefits of Functional Programming
Understand how functional programming reduces cognitive load by using pure functions and minimizing working memory usage. Learn how this approach in PHP simplifies code evaluation, improves testing, and enables easy parallelization for efficient and maintainable applications.
We'll cover the following...
Cognitive load-reducing ability
Functional programming reduces the cognitive burden of writing code. Composing pure functions limits the mental effort required to perform tasks.
The human brain has a variable, but small number of shared memory resources for discrete working that we refer to as memory quanta. Working memory, the short-term memory optimized for temporary storage, is a limited resource. Each variable written in a computer program occupies at least one quantum of that limited memory.
Example
The snippet below contains three variables declared and evaluated by the PHP interpreter.
Functional programming relieves the burden of processing variable information. A simple function can suffice here:
The anonymous add function assigned to the add variable eliminates the need for the first and second variables. The lambda function above effectively frees up working memory and simplifies the problem of adding two numbers.
Tip: Eric Elliott, a brilliant technologist, wrote an article titled “Composing Software: An Introduction” that highlights some of the benefits of functional programming. It’s certainly worth a read.
Code that adapts to our cognitive limitations is naturally easy to evaluate, transform, and test. Furthermore, functional code is easy to split among multiple processors, which is a common method of concurrent parallelization.