Best of Both Worlds and Combining FP Paradigms with OOP

"Objects are closures with multiple methods, closures are objects with a single method.
So yes [OOP and FP can be used together]."                  
                                                                                        - Erik Meijer

In previous chapters, we talked mostly about Functional Programming (FP). We learned various techniques and paradigms of FP. In contrast, we barely touched on object-oriented programming (OOP). Mostly, we talked about the disadvantages of imperative programming. In practice, most of us have to work on applications that are designed by OOP principles. The reality is that even if we do not like OOP, we are stuck with it. For instance, in iOS and Mac OS development, we have to deal with Cocoa and Cocoa Touch frameworks that are designed by OOP principles.

On the other hand, we are familiar with OOP because most of us learned it at some point and some of us find it natural to model real-world problems with it.

There is a huge discussion about the benefits of one paradigm over the other. Some claim that they can be unified; some claim that they are exclusive and we should choose one paradigm over the other. Also, different programming languages and their communities follow different approaches.

For instance, Haskell is a purely FP language, and it is almost impossible to do OOP with it. In fact, it is absurd to do OOP with it. On the other hand, languages such as Java, Ruby, Python, and C# are OOP languages with limited FP capabilities. There are also languages such as Scala that mix OOP with FP and embrace both worlds.

How would we picture Swift in these settings? We know that Swift is not a pure FP language and has FP capabilities, but we need to further evaluate it in this regard.

In addition to these, the Swift programming community has been introduced to another paradigm: protocol-oriented programming (POP). Furthermore, Functional Reactive Programming (FRP) became very popular and is loved by lots of developers.

What are the advantages and disadvantages of one paradigm over the others? How would we design our applications to benefit from all these paradigms? These are the questions that we will try to answer in this chapter. Hence, we will start by introducing OOP, POP, and FRP, and then we will mix OOP paradigms with FP.

This chapter will cover the following topics by coding examples:

  • A brief introduction to OOP paradigms
  • OOP design patterns/principles
  • A brief introduction to POP
  • Functional reactive programming (FRP)
  • Mixing OOP and FP
..................Content has been hidden....................

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