At RailsConf 2019, we attended an interesting lecture called “Sprinkles of Functional Programming.” WebRTC Ventures aims to use the best approaches for our solutions, so I was excited for this lecture. The lecture discussed two concepts: object-oriented and functional programming.
Object-oriented programming is a style that allows programmers to translate the behavior of things in real life to code that is understood by a computer. This presents concepts like class, object, inheritance, encapsulation, abstraction, and polymorphism.
Functional programming takes into account data and how it will change as we build our application. Many programming languages are specifically built-in to take advantage of this paradigm that “handles symbolic computation and list processing applications.”
After showing us different scenarios where object-oriented and functional programming may shine, lecturer John Schoeman took us on an imaginary journey creating a web app for a client.
The Lecture
The lecture started by creating a new rails web app that stores products and allows its users to upload CSV files instead of manually creating them. Until this point, this is not far from what we see in our day-to-day developer lives.
Object-oriented and functional programming implementations diverge. First, we see the object-oriented implementation here:
And we see the functional programming implementation here:
As you can see here, the object-oriented implementation is all about behavior whereas the functional implementation is more about handling data.
The requirement changes and now the web app needs to allow Excel files to import.
Object-oriented implementation changes to a new class named ProductDataImporter, where we store the logic of the import functionality. The change in the code looks like the following:
Now the importer controller looks like this:
The functional programming changes are as follows:
And the read_file function is now:
In this lecture, it was clear that all these small changes were directed to specific data manipulation instead of changes in the code to simulate the behavior of the reality creating new classes and their functionality.
In conclusion, neither of the paradigms is better or worse than the other. It comes down to how the requirements will take place and how the data will change during the implementation. Luckily, Ruby and Rails have everything we need to create a web app with object-oriented or functional programming in mind.