Chapter 10. Functional Design Patterns – The Deep Theory

The Scala programming language is a hybrid between a functional and object-oriented language. Most of the object-oriented design patterns are still applicable. However, in order to facilitate the full power of Scala, you also need to be aware of the purely functional aspects of it. When using the language and reading tutorials or best practices, developers will most likely notice terms such as monoids, monads, and functors appearing more often as the problems become harder or the solutions are desired to be the more elegant. In this chapter, we will focus on the following functional design patterns:

  • Monoids
  • Functors
  • Monads

There are a lot of resources on the preceding topics all over Internet. The problem is that many of them are extremely theoretical and hard to understand by someone who is not really familiar with mathematics and more specifically—category theory. As it happens, in practice, many developers lack the deep mathematical background needed to grasp the topics, and it is not unusual to completely avoid these concepts in the code.

In my experience, most of the Scala developers I know have tried to read tutorials on the topics covered in this chapter, and they've found these topics difficult to understand and have given up. Expert mathematicians seem to find these concepts much easier. However, despite repeated attempts at understanding, most people admit that they are not completely comfortable with the deep functional programming theory. In this chapter, we will try and present this theory in a way that is easy to understand, and we will give an idea of how and when to apply the theory.

Abstraction and vocabulary

A big part of programming is abstraction. We find common functionality, laws, and behavior and encapsulate them into classes, interfaces, functions, and so on, which are abstract and allow code reuse. Then, we refer to them and reuse them to minimize code duplication and the possibility of errors. Some of these abstractions are more common than others and are observed in different projects and used by more people. These abstractions lead to the creation of a common vocabulary, which additionally helps in communication and understanding. Everybody knows certain data structures such as trees and hash maps, and so there is no need to get into detail about them because their behavior and requirements are well known. Similarly, when someone gains enough experience in design patterns, they can see them and easily apply the patterns to the problems they are trying to tackle.

In this chapter, we will try to look at monoids, monads, and functors from a point of view, which will teach us how to recognize them and when to use them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.67.5