I have been reading numerous articles about OOP and FP and comparison of these two recently. There are lots of differences and pro/cons for each of them but one important and interesting thing I recently found out was the fact that how tangled behavior and data are in OOP. I have been writing OO code for years, but I had not found out this until I read about FP and the way it handles data/behavior.
When you write a software in an OO approach, you must relate every behavior to a single isolated data entity (or class) in the business domain of the application. For example, when writing a code to send email, you have a data entity called "Email Message" and a behavior "Send a message". There is no way for you to define these two separately. By separately I mean being able to invoke "Send Email Message" functionality without an "Email Message" object. Of course, you need a message when you want to send one, but this is a difference in the way we organize and approach things in OOP. When writing software in OO approach, you MUST define each behavior under one and exactly one class.
Question is, what if we cannot fit a behavior in this pattern? What if it doesn't make sense or it is confusing to attach a behavior to one and only one class?
Considering above example about sending an email message, what happens if we have other entities in the application like Sender, Recipient, and Storage. Then where should I put "Send email message" functionality? Each one of the below candidates can be an acceptable place for putting this behavior.
- You can put "Send" method in "Message" class:
- It can also be placed inside Recipient class:
- It can also be part of Sender class:
- It can be part of a separate class. For example MessageBroker:
The advantage of Functional Programming approach is that you don't have to bind each behavior to one class. They are completely separated. So you can define and use them separately. This type of modeling is more consistent with the way we think about software world concepts.
Of course for things which exist in the physical world, this is less of an issue (A car is the only object which can do the "Start" functionality). But for more abstract concepts which can only be found in the software world, I think FP approach makes more sense.