OOP Vs FP
In the third chapter of the SICP book titled "Modularity, Objects, and State," the book begins by explaining how to structure a system to be modular.
It states that there are two ways to achieve this:
Object-oriented approach
Stream Processing approach (Functional Programming)
Object-oriented approach:
Here, we start thinking of the system as a collection of objects, each object having a set of properties and a set of actions, and that the behavior of this object changes over time. For example: a person has a weight and height.
At the age of 1, the weight is 10 kg and the height is 30 cm.
At the age of 10, the weight is 40 kg and the height is 100 cm.
Thus, each object has a state that represents it at the current time, and this state consists of local variables that store the state. Returning to the previous example:
Class Person {
float Age;
float weight;
}
Of course, this state must be protected so that no one can change it (other than the object itself) and thus change the behavior of this object. So, how is it protected? This is where a famous term called data hiding comes into play, which allows me to control how the object can be changed.
In summary, Object-oriented programming is about protecting the state of an object.
Of course, this approach has many problems because it relies on assignment, making objects mutable data, which can cause race conditions and lead to problems during concurrent execution.
Stream Processing approach:
Here, we think of the system as a flow of information in the system rather than thinking of it as individual objects. So, the system is a set of data streams that pass through many stages, each stage taking a stream as input, performing some operation on it, and producing an output stream that goes inside another stage.
This approach does not use assignment, so there is no state, and therefore no fear of race conditions or problems with concurrent execution.
The summary is that OOP tries to protect the state while FP eliminates the state, which is the fundamental difference between the two paradigms.
Subscribe to my newsletter
Read articles from Mohamed Mahgoub directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by